I am trying to learn immutablejs with reactjs. I have a list of items with checkbox for each item. I want the functionality like when checkbox is clicked a checkmark should be shown and also some text like checked. I tried but when i check the first checkbox, second checkbox gets checked.
Here is my code
class AddRemoveCheckbox extends React.Component{
constructor(){
super();
this.state = {
checked: Immutable.List([])
}
}
handleChange(e, key) {
console.log('key', key);
const { checked } = this.state;
if (e.target.checked) {
this.setState({
checked: checked.push(key)
})
} else {
this.setState({
checked: checked.pop(key)
})
}
}
render() {
console.log('items');
const { checked } = this.state;
console.log('checked', checked.has('0'));
const items = this.props.items.map((item,key) => {
return (
<li key={key} style=>
<input
type="checkbox"
checked={checked.has(key)}
onChange={(e)=>this.handleChange(e, key)}
/>
{item}
</li>
)
})
return (
<div>
Items:
{items}
{ checked.has('0') ? 'Checked' : 'Unchecked'}
</div>
);
}
}
ReactDOM.render(<AddRemoveCheckbox items={['item1', 'item2'] } />, document.getElementById('root'));
I have this code on jsbin too
Aucun commentaire:
Enregistrer un commentaire