Material UI checkbox component not working

Hi Guys,

I am using material UI checkbox components inside a react component. I can’t get the basic checked/unchecked function working although I believe I did and checked everything. Anyone care to help? here’s the code:


class SplitEqually extends React.Component {
  constructor(props) {
    super(props);
    let checked = this.props.contributors.map((contributor) => contributor.id)
    this.state = {
      checkedContributors: this.props.contributors,
      checkedId: checked,
    };
  }
  handleChange = (e, contri) => {
    let checkedId = this.state.checkedId.includes(contri.id)
      ? this.state.checkedId.filter((id) => id !== contri.id)
      : [...this.state.checkedId, contri.id];
     console.log(checkedId)
    let checkedContributors = this.state.checkedContributors.filter((contri) =>
      checkedId.includes(contri.id)
    );
    this.setState(checkedId);
  };

  render() {
    const { classes, contributors } = this.props;
    const { checkedContributors, checkedId } = this.state;
    return (
      <div className={classes.splitUnequally}>
        {contributors.map((contributor, i) => {
          let { id, name } = contributor;
          console.log(checkedId.includes(id));
          return (
            <div className={classes.list} key={id}>
              <div className={classes.avatar}></div>
              <FormControlLabel
                labelPlacement="start"
                control={
                  <Checkbox
                    onChange={(e) => this.handleChange(e, contributor)}
                    name={name}
                    checked={checkedId.includes(id)}
                  />
                }
                label={name}
              />
            </div>
          );
        })}
        <br></br>
      </div>
    );
  }
}

checkedContributors state variable is an array of object, each object defining one user with a unique id property.
CheckedId state variable is an array which contains unique id of only those users who are checked.

I was using the wrong syntax for setting the state. It should have been this.setState({checkedId}); and not this.setState(checkedId);. Correcting this resolved the issue

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.