Reputation: 53
var RoomList = React.createClass({
getInitialState: function() {
return { liked: false };
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'empty' : 'full';
var inOffice = this.props.data.map((function(comment, index) {
return(
<button type='button' key={index} className ={text} onClick={this.handleClick}>
{comment.room}
</button>
);
}).bind(this));
return (
<ul className='rooms'>{inOffice}</ul>
);
}
});
Problem: This is only part of my code... I load a list of 5 value pairs: {"room":101},{room:102}... I create a button for each. When I click on a button, it should change color from red to green or green to red, however, it changes all of the buttons. How can I change the color of just one of my buttons?
Upvotes: 4
Views: 7665
Reputation: 7028
Create buttons as a separate React Components and handle onClick isolated between them. RoomList becomes just simple list of RoomElement components.
var RoomElement = React.createClass({
getInitialState: function() {
return { liked: false };
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
return (
<button type="button" key={index} className={ this.state.liked ? 'empty' : 'full' } onClick={this.handleClick}>
{this.props.text}
</button>
);
}
});
var RoomList = React.createClass({
render: function() {
return (
<ul className="rooms">
{this.props.data.map(function(comment, index) {
return <RoomElement key={index} text={comment.room} />
}, this) }
</ul>
);
}
});
Upvotes: 3