Search code examples
reactjsreact-nativereact-native-maps

Struggling using zIndex to order views


I am trying to load a component on top of another. In my demo I have two screens that are conditionally rendered using a slider button(I would use a simple text button but I want to make sure the animation works). Screen 1 is just a grey screen and screen 2 is a screen of react native maps being rendered.

I would like the slider button to be on top of the map. I need the map to be full page. Originally I tried using zIndex but that is not working.

I have a working demo here

App.js

export default class Home extends React.Component {
 
  constructor(props) {
    super(props)
    this.state ={
      visible: true,
      whichComponentToShow: 'Screen1'
    };
}

goToMap = () => {
  this.setState({whichComponentToShow: 'Screen2'})
}
goToList = () => {
  this.setState({whichComponentToShow: 'Screen1'})
}

  render(){

    const SliderRender = (
      <Slider
        renderMap={this.goToMap.bind(this)}
          renderList={this.goToList.bind(this)}
          key="slider"
          style={{zIndex: 10}}
         />
      );
    
     if(this.state.whichComponentToShow === 'Screen1'){
      return(
       <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>  
        
        {SliderRender}

          <ListHome
            renderMap={this.goToMap.bind(this)}
            renderList={this.goToList.bind(this)}
          />
        </View>
      );
    }
    else if(this.state.whichComponentToShow === 'Screen2'){
      return(
       <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>

        <MapHome
          renderMap={this.goToMap.bind(this)}
          renderList={this.goToList.bind(this)}
          
        />

        {SliderRender}
 
       </View>
      );
    }
 }
 }
 

Solution

  • You can use a View with position: absolute to wrap the slider buttons.

    render() {
      const { whichComponentToShow } = this.state;
    
      return(
        <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
          {whichComponentToShow === 'Screen1' && <ListHome />}
          {whichComponentToShow === 'Screen2' && <MapHome />}
          <View style={{position: 'absolute', top: 0, left: 0, right: 0}}>
            <Slider
              renderMap={this.goToMap}
              renderList={this.goToList}
            />
          </View>
        </View>
      );
    }