Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS MaterialUI Checkboxes- setting state within onCheck()

Using material-ui 0.15.3 and react 15.3.0.

I have a Checkbox component and want to use this.setState within its onCheck function.

It became apparent pretty quickly that I had to manually pass something into the Checkbox's checked prop. If I don't, then I cannot use setState. If I try to do so, then the visual component of the checkbox wont update. E.g. I click the checkbox and it stays empty. My first question is why? Why can't I keep this as an uncontrolled component? Why must I pass something into the checked prop?

    <Checkbox
    label="1"
    style={styles.checkbox}
    onCheck={this.handleCheck.bind(this)}
    checked={this.state.box1} // if this is not supplied then I cannot use setState within handleCheck()

handleCheck():

  handleCheck(event, checked) {
    this.setState({
        box1: checked 
        someState: someValue 
    });
 }

Now I have multiple checkboxes, so my second question is, how can I structure this so it is as clean as possible? Will I need to have a separate state variable for each checkbox with individual handleCheck() functions? I feel like that would get messy very quickly. e.g. (state for box1, box2, box3 etc.)

like image 226
Rolodecks Avatar asked Dec 25 '22 03:12

Rolodecks


1 Answers

Will I need to have a separate state variable for each checkbox?

Yes, but it doesn't need to be cumbersome. It could be an array of ids that correspond to a particular checkbox.

Will I need to have a separate handleCheck() functions?

Certainly not, a single function will do. Just pass the id along.

Here's an example imagining you have a variable number of checkboxes:

handleCheck(id) {
  let found = this.state.activeCheckboxes.includes(id)
  if (found) {
    this.setState({ 
      activeCheckboxes: this.state.activeCheckboxes.filter(x => x !== id)
    })
  } else {
    this.setState({ 
      activeCheckboxes: [ ...this.state.activeCheckboxes, id ]
    })
  }
}

render() {
  return (
    <div>
      {this.state.aBunchOfCheckboxes.map(checkbox =>
        <Checkbox
          label={checkbox.label}
          onCheck={() => this.handleCheck(checkbox.id)}
          checked={this.state.activeCheckboxes.includes(id)}
        />
      }
    </div>
  )
}
like image 180
azium Avatar answered Jan 05 '23 15:01

azium