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={{ listStyle: 'none' }}>
<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
I would recommend using an Immutable Set instead of List. This lets you deal purely with values instead of messing with indices.
Your original issue was that you were
pop
ing the last item from the list, no matter what it was. You were also checking indices of the list withhas
instead of values.constructor:
handleChange:
render:
and
I forked your JSBin.