I've found a couple questions on here that sort of answer the question,
but they do not allow me to render a component with a checkbox.
What I'd like is something like this,
render: function () {
var rows = [<ChildElement key={1} />, <ChildElement key={2} />];
return (
<ParentElement>{rows}</ParentElement>
);
}
where my ChildElements each have their own check boxes that can be set to checked=true
or checked=false
whenever a global checkbox is checked or unchecked on the ParentElement.
Any suggestions? Cheers
I put together a gist for you to try but the basic idea is to maintain the state of the checkboxes in the parent and have a callback in the child that passes up its changed state.
http://jsfiddle.net/69z2wepo/4785/
var Row = React.createClass({
getInitialState: function() {
return {
checked: false
};
},
checkIt: function() {
this.props.callback(this.props.index, !this.props.checked);
return;
},
render: function() {
return (
<tr>
<td><input type="checkbox" checked={this.props.checked} onChange={this.checkIt} /></td>
<td>{this.props.obj.foo}</td>
</tr>
);
}
});
var Table = React.createClass({
getInitialState: function() {
var rowState =[];
for(var i = 0; i < this.props.rows.length; i++) {
rowState[i] = false;
}
return {
checkAll: false,
rowState:rowState
};
},
checkRow: function (id,value) {
this.state.rowState[id] = value;
if (this.state.checkAll) {
this.state.checkAll = !this.state.checkAll;
}
this.setState({
rowState: this.state.rowState,
checkAll: this.state.checkAll
});
},
checkAll: function () {
var rowState =[];
var checkState = !this.state.checkAll;
for(var i = 0; i < this.state.rowState.length; i++) {
rowState[i] = checkState;
}
this.state.checkAll = checkState;
this.setState({
rowState: rowState,
checkAll: this.state.checkAll
});
},
render: function() {
var self = this;
var rows = _.map(this.props.rows, function( row,index) {
return (<Row obj={row} index={index} key={row.id} checked={self.state.rowState[index]} callback={self.checkRow} />);
});
return (
<div className="table-holder container">
<input type="checkbox" checked={this.state.checkAll} onChange={this.checkAll} />
<table className="table">{rows}</table>
</div>
);
}
});
var rows = [
{
'id' : 1,
'foo': 'bar'
},
{
'id' : 2,
'foo': 'baarrrr'
},
{
'id' : 3,
'foo': 'baz'
}
];
React.render(<Table rows={rows}/>, document.getElementById('container'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With