mardi 16 avril 2019

Update checkboxes' state but not immediately

I have a react-table with many columns. When user clicks on a column's header, a modal appears with checkboxes options where user can select which columns to show or hide.

image

Until now, when I click on a checkbox, its state immediately changes and the modal disappears. This is an acceptable approach, but not exactly what I want. So, what I currently do is this:

this.state = {
  data: [],
  columns: {
    displayName: true,
    phoneNumber: true,
    balance: true,
    currencyCode: true,
  }
}
this.handleInputChange = this.handleInputChange.bind(this);
}

handleInputChange = (key) => {
  this.setState({ [key]: !this.state[key] });
}

render() {
const { data} = this.state;
const { displayName, phoneNumber, balance, currencyCode } =this.state.columns;

const columns = (
  <div style=>
    <ul>
    {Object.keys(this.state.columns).map((key) => (
      <li key={key}>
        <input
          name={key}
          id={`checkbox-${key}`}
          type="checkbox"
          checked={this.state.columns[key]}
          onChange={(key) => this.handleInputChange(key)}
        />
        <label>{content[lang][key]}</label>
      </li>
    ))}
    </ul>
  </div>
);

What I would like to do is that user can select columns not one by one, but many columns at once, so that state will not be updated immediately in the onChange event, but instead, by clicking on a 'OK' button. So, what I am thinking of is to make a function that returns an array of keys. Each time user clicks on a checkbox (onChange event), another key is pushed to the array. Something like this:

statesToChange = (key) => {
  const array = [];
  array.push(key);
  //console.log(array);

}

When user is done and clicks on the OK button, that's when the state of each column (checkbox) will be updated. Is this approach correct? Any help would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire