Search code examples
react-native

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?


Solution

  • 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>