bleepmeh
bleepmeh

Reputation: 1037

zIndex isn't working for a react native project

I'm trying to have a card shown on top of a card in React Native and set zIndex = 1 for the top card and zIndex = 0 for the bottom card and placed them in a view like below:

<View style={{paddingVertical: MARGIN_1, justifyContent: 'center'}}>
  {this.props.subscribed ? (
    <CardSubscribe
      style={{zIndex: 2}}
    />
  ) : (null)}
  {this._renderTextItems()}
</View> 

However, there's no overlap between two cards. The bottom card starts after the top card:

enter image description here

I have also tried to debug with inspector and it shows the top card has the property of zIndex = 1 :

enter image description here

and the bottom card has the property of zIndex = 0 :

enter image description here

I have also tried to place the top card after the bottom card but it just shows below the bottom card, like zIndex isn't doing anything. How should I fix this?

Upvotes: 32

Views: 48673

Answers (3)

Vaibhav Acharya
Vaibhav Acharya

Reputation: 11

Put the element with a higher stack level after the one with lower stack level in the document tree.

const App = () => (
  <View style={{ flex: 1 }}>
    // View 1 (Higher View)
    <View style={{ backgroundColor: 'yellow',  flex: 1 }} />

    // View 2 (Lower View)
    // View 2 is placed after View 1
    <View style={{ position: 'absolute',  zIndex: 1 }} />
  </View>
);

Upvotes: 0

Lalit kumar
Lalit kumar

Reputation: 2485

z-index working fine in IOS. but again you will get isssue in android. In android z-index is not working you need to use elevation. But please do not forget to add z-index.

<TouchableOpacity
              style={{
                alignSelf: 'center',
                position: 'absolute',
                right: 10,
                top: 10,
                zIndex: 15,
                elevation: (Platform.OS === 'android') ? 50 : 0
              }}
              onPress={() => {}}
            >
              <Image
                source={require('dummy.png')}
              />
            </TouchableOpacity>

Upvotes: 66

Pritish Vaidya
Pritish Vaidya

Reputation: 22209

In React Native we have position: relative by default. If you want to make the correct use of zIndex, you might need to add position: 'absolute', for them to overlap as described in your use case.

For example:

<View style={{flex: 1}}>
               <View style={{width: 200, height: 200, zIndex: 1, position: 'absolute', backgroundColor: 'red'}} />
               <View style={{width: 200, height: 200, zIndex: 2, position: 'absolute', backgroundColor: 'blue'}} />
 </View>

Upvotes: 24

Related Questions