vendredi 6 septembre 2019

React: ChecBox checked state programmatically not reflecting checkbox state

I have a react table where I am showing and hiding columns individually on a checkbox click. If I remove the checked property from the checkbox input element things work as expected. However if I add it in and track the checked property using state, the check box will click off the first time but not back on but the column state does update and reappears.

Eventually my end goal is to be able to click the "remove all columns" option at the top of this list to show hide all columns. The show/hide piece works but the checking of the boxes does not.

updateColumnShow = fieldName => {
  this.setState({ [fieldName]: !fieldName });
  this.setState(state => {
    const columns = state.columns.map(column => {
      if (column.Header === fieldName) {
        column.show = !column.show;
        return column;
      } else {
        return column;
      }
    });
    return { columns };
  });
};

render() {
  return (
    <div>
      {this.state.columnList.map(listItem => (
        <li key={listItem}>
          <input
            id={listItem}
            checked={this.state[listItem]}
            className="form-check-input"
            type="checkbox"
            name={listItem}
            onChange={() => this.updateColumnShow(listItem)}
          />
          <label>{listItem}</label>
        </li>
      ))}
    </div>
  );
}

I have created a CodeSandbox to demo the issue.

What am I overlooking?




Aucun commentaire:

Enregistrer un commentaire