Matty Matty - 1 month ago 9
CSS Question

React. Specifying the Index of Only One Div

Below I have one component that seems to work fine except that when I click on one of the div's all the div's change. I can't seem to figure out if I need to add a key, ref, or index element. I have tried all three to no avail. I think the ES6 is throwing me off. So essentially, I am looking to change the color of only the div that is clicked on.

import React from 'react';
class AwesomeComponent2 extends React.Component {
constructor(props){
super(props);
this.state = {
onClicked: false
}
this.handlerButtonOnClick = this.handlerButtonOnClick.bind(this);
}
handlerButtonOnClick(event){
alert(event.target);
this.setState({
onClicked: true
});
}
render() {
var _style;
if (this.state.onClicked){ // clicked button style
_style = {
backgroundColor: "#FAE456"

}

}
else{ // default button style
_style = {
backgroundColor: "#B3B3B3"
}
}
return (
<div className="main-container">
<div onClick={this.handlerButtonOnClick}
style={_style} className ="nineBoxes"> </div>
<div onClick={this.handlerButtonOnClick}
style={_style} className ="nineBoxes" className="nineBoxes"> </div>
<div onClick={this.handlerButtonOnClick}
style={_style} className ="nineBoxes" className="nineBoxes"> </div>
</div>
);
}
}


The link below didn't clarify this issue for me.

Getting Index of onClick target with ReactJs

Answer

You can pass arguments to your onClick functions.

<div onClick={() => this.handlerButtonOnClick('div1')}>

Save that value in state:

handlerButtonOnClick(div) {
  this.setState({
    clickedDiv: div
  });
}

Then conditionally apply that style in render

<div style={this.state.clickedDiv === 'div1' ? clickedStyle : defaultStyle}>