Steve
Steve

Reputation: 11

React.js - Both images disappear onClick - how do I make only 1 disappear at

I'm trying to make an image disappear on React.js but if there are 2 images and one is clicked, they both disappear. I just need one to disappear at a time when they are clicked. I'm adding a class that will 'display:none' when clicked on.

class Home extends Component {
constructor(props) {
  super(props);
  this.state = {addClass: false}
}
handleClick() {
    this.setState({addClass: !this.state.addClass});
  }
render () {
    let clickedClass = ["beer"];
    if(this.state.addClass) {
        clickedClass.push('gone');
    }
    return (
        <div>
                    <img id="beer1" className={clickedClass.join(' ')} src={('/images/beer1.png')} onClick={(e) => this.handleClick(e)}/>
                    <img id="beer2" className={clickedClass.join(' ')} src={('/images/beer2.png')} onClick={(e) => this.handleClick(e)}/>
        </div>
    )
}

}

Upvotes: 1

Views: 778

Answers (1)

Artur Carvalho
Artur Carvalho

Reputation: 7167

The state is common, so when you toggle it, it applies to both images.

Option 1: Create a component that you pass the image and has a state. When you create 2 components, there will be 2 independent states. Usually this is the way to go.

Option 2: On the state have 2 properties. E.g.:

 this.state ={showTopImage: true, showBottomImage: false}

and after, handle the click depending on which image you clicked.

Upvotes: 1

Related Questions