Last active
August 29, 2015 14:27
-
-
Save paulserraino/3ab9dd05893954c0982e to your computer and use it in GitHub Desktop.
Updating a collection of child components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var React = require('react'); | |
/** | |
* Input | |
*/ | |
var Input = React.createClass({ | |
getInitialState: function () { | |
return { name: this.props.name || '' } | |
}, | |
update: function (e) { | |
this.setState({ | |
name: e.target.value | |
}, function () { | |
// pass state change to parent onChange method | |
if (this.props.onChange) { | |
this.props.onChange(this.state.name, this.props.index, e); | |
} | |
}.bind(this)); | |
}, | |
render: function () { | |
return ( | |
<div> | |
<input type="text" onChange={this.update} value={this.state.name} /> | |
</div> | |
); | |
} | |
}); | |
/** | |
* InputList - list of Input components | |
*/ | |
var InputList = React.createClass({ | |
getInitialState: function () { | |
return { | |
names: this.props.names || [{}] | |
} | |
}, | |
submit: function (e) { | |
e.preventDefault(); | |
console.log(this.state.names); | |
}, | |
update: function (name, index) { | |
this.setState(function (state) { | |
state.names[index] = name; | |
}); | |
}, | |
addInput: function (e) { | |
e.preventDefault(); | |
this.setState({ | |
names: this.state.names.concat({}) | |
}); | |
}, | |
render: function () { | |
var list = this.state.names.map(function (o, i) { | |
return ( | |
<Input key={i} index={i} name={o.name} onChange={this.update} /> | |
); | |
}.bind(this)); | |
return ( | |
<div> | |
{list} | |
<button onClick={this.addInput}>+ add</button> | |
<button onClick={this.submit}>submit</button> | |
</div> | |
); | |
} | |
}); | |
React.render(<InputList />, document.getElementById('app')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment