If you only want to keep 1 item active, you can keep a reference to the selected item in your state. Then you can write an onClick callback to change the selected item.
var MyList = React.createClass({
getInitialState: function(){
return {
data: ['foo', 'bar', 'baz'],
selected: null
}
},
selectItem: function(el){
this.setState({selected: el});
},
renderItem: function(el){
var className = this.state.selected === el ? 'active' : 'inactive';
var onClick = this.selectItem.bind(this, el);
return <li key={el} className={className} onClick={onClick}>{el}</li>;
},
render: function() {
return (
<ul>
{ this.state.data.map(this.renderItem) }
</ul>
);
}
});
ReactDOM.render(
<MyList />,
document.getElementById('container')
);
If you want to be able to toggle between active and inactive on each list item, you can use the same approach but keep an object as your selected state:
getInitialState: function(){
return {
data: ['foo', 'bar', 'baz'],
selected: {}
}
},
selectItem: function(el){
var selected = this.state.selected;
selected[el] = !selected[el];
this.setState({selected: selected});
},
And modify your renderItem function accordingly:
var className = this.state.selected[el] ? 'active' : 'inactive';
var onClick = this.selectItem.bind(this, el);