<div id="root"></div>
li > * {
display: inline-block;
width: 8em;
}
View Compiled
// Container Component
const UserListContainer = React.createClass({
getInitialState: function() {
return {
users: [
{id:1, name:'Ryan', active:true},
{id:2, name:'Michael', active:true},
{id:3, name:'Dan', active:true}
]
}
},
render: function() {
return (<UserList users={this.state.users} toggleActive={this.toggleActive} />);
},
toggleActive: function(user) {
// State should never be mutated (changed) directly. So instead of calling
// this.setState() and chanching the this.state directly, we'll make a copy of
// the state, change the copy, then update the state with the copy
// Get the index of our state that matches our user
var index = this.state.users.indexOf(user);
// Make a copy of the state
var newState = Object.assign({}, this.state);
// newState is a shallow copy of this.state, so user object should be the same
console.log('user === newState.users[index]', user === newState.users[index]);
// Toggle the "activeness"
newState.users[index].active = !newState.users[index].active
console.log('newState.users[index].active', newState.users[index].active);
console.log('user.active', user.active);
// Set the state to the new state
this.setState(newState)
}
});
// Presentational Component
const UserList = React.createClass({
render: function() {
let _this = this;
return (
<ul className="user-list">
{this.props.users.map(function(user) {
// The `.bind()` method ensures that when `toggleActive()` is called,
// the first argument to it will be the `user`
return (
<li key={user.id}>
<a href="#">{user.name}</a>
<span>{user.active ? 'Active' : 'Not Active'}</span>
<button onClick={_this.props.toggleActive.bind(null, user)}>Toggle Active</button>
</li>
);
})}
</ul>
);
}
});
ReactDOM.render(<UserListContainer />, document.getElementById('root'))
View Compiled
This Pen doesn't use any external CSS resources.