Search code examples
cssreactjsstatez-index

React, z-index for each array element


Not long ago here I recieved answer, how increase each img as member of array. Somehow the same principle don't wokrs for z-index (increaced img should lie on top of the rest), though console displays that z-index changed. Why? enter image description here

class Article extends React.Component{  
    constructor(props) {
        super(props)
        this.state = {showIncreaced: null}

    this.getImgStyle = this.getImgStyle.bind(this);
    this.increase = this.increase.bind(this);
    }

    increase (incId) {
        this.setState({showIncreaced: incId})
    }

  getImgStyle (id) {
    return {
      width: '20vw',
      marginRight: '0.5vw',
      marginLeft: '0.5vw',
      zIndex: this.state.showIncreaced === id ? '10' : '0',
      transform: this.state.showIncreaced === id ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
    };
  }

    render(){   
        const TipStyle={                        
                marginBottom: '10px'
        }

    return(                     
        <div style={TipStyle}>                      
          <h2 style={{marginBottom: '1px'}}>{this.props.name}</h2>
          <div>
        {[1,2,3].map((id) => {
            return <img style={this.getImgStyle(id)} src={this.props[`img${id}`]} onMouseOver={this.increase.bind(this, id)} onMouseOut={this.increase} />
        })}                         
          </div>
        </div>                  
); 
}
}

https://jsfiddle.net/Nata_Hamster/fbs3m4jL/


Solution

  • add position: 'relative', to the object returned by getImgStyle because z-index works only when postion is set to something else than static (its default value). The easiest way is to use relative because the element is still part of the document flow.

    https://jsfiddle.net/fbs3m4jL/7/