I'm new to React. I'm trying to change the color of one particular "li" that was selected, but instead it changes color of all "li".
Also when another "li" is clicked I want the first "i" to be not active again.
here is the code: http://codepen.io/polinaz/pen/zNJKqO
var List = React.createClass({
getInitialState: function(){
return { color: ''}
},
changeColor: function(){
var newColor = this.state.color == '' ? 'blue' : '';
this.setState({ color : newColor})
},
render: function () {
return (
<div>
<li style={{background:this.state.color}} onClick={this.changeColor}>one</li>
<li style={{background:this.state.color}} onClick={this.changeColor}>two</li>
<li style={{background:this.state.color}} onClick={this.changeColor}>three</li>
</div>
);
}
});
ReactDOM.render(
<List/>,
document.getElementById('app')
);
Since you don't have any identifiers on you list items you activate/deactivate them all every time. You need to reference each of them in a different way, then you can set the color individually. This is one example
var List = React.createClass({
getInitialState: function(){
return { active: null}
},
toggle: function(position){
if (this.state.active === position) {
this.setState({active : null})
} else {
this.setState({active : position})
}
},
myColor: function(position) {
if (this.state.active === position) {
return "blue";
}
return "";
},
render: function () {
return (
<div>
<li style={{background: this.myColor(0)}} onClick={() => {this.toggle(0)}}>one</li>
<li style={{background: this.myColor(1)}} onClick={() => {this.toggle(1)}}>two</li>
<li style={{background: this.myColor(2)}} onClick={() => {this.toggle(2)}}>three</li>
</div>
);
}
});
ReactDOM.render(
<List/>,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
<!-- This div's content will be managed by React. -->
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With