how do i check and uncheck input checkbox using immutable js

377 Views Asked by At

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

http://jsbin.com/fusoxos/edit?js,console,output

1

There are 1 best solutions below

5
On

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 poping the last item from the list, no matter what it was. You were also checking indices of the list with has instead of values.

constructor:

this.state = {
  checked: Immutable.Set()
}

handleChange:

if (e.target.checked) {
  this.setState({
    checked: checked.add(key)
  })
} else {
  this.setState({ 
    checked: checked.remove(key)
  })
}

render:

checked={checked.includes(key)}

and

  { checked.contains(0) ? 'Checked' : 'Unchecked'}

I forked your JSBin.