Skip to content

Instantly share code, notes, and snippets.

@paulserraino
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulserraino/3ab9dd05893954c0982e to your computer and use it in GitHub Desktop.
Save paulserraino/3ab9dd05893954c0982e to your computer and use it in GitHub Desktop.
Updating a collection of child components
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