Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally disabled React Checkboxes

I am building out a listing of checkboxes and only want the user to be able to select 2 checkboxes and then it will disable the checkboxes. I have a disabled prop which I can pass a boolean but having trouble with the logic to disable the checkbox.

<UISelectableButton
    key={i}
    block={true}
    value={workflow}
    disabled={selectedRevisions > 1 && true}
    onSelectedChange={this.onSelectedChange}
    onClick={() => this.handleRevisions(workflow)}
    type="checkbox"
/>

For the onSelectedChange I have a function that will hold the index of how many checkboxes are currently selected. I can easily disable the buttons with a ternary operator by doing selectedRevisions > 2 then anytime there are more than 2 items selected then I disable the buttons. The problem with this is that will disable all the buttons and I don't want to disable any buttons that have been selected. Is there a way to check if the checkbox has been selected and still pass disabled a boolean and not a function.

like image 618
James Zilch Avatar asked Aug 07 '18 01:08

James Zilch


1 Answers

You could keep an object in state that keep track of the checkbox values, and in your render method you can check if there are 2 or more checkboxes that are checked and use this to disable the others.

Example

class App extends React.Component {
  state = { checked: {} };

  onSelectedChange = index => {
    this.setState(previousState => ({
      checked: {
        ...previousState.checked,
        [index]: !previousState.checked[index]
      }
    }));
  };

  render() {
    const { checked } = this.state;
    const checkedCount = Object.keys(checked).filter(key => checked[key]).length;
    const disabled = checkedCount > 1;

    return (
      <div>
        {Array.from({ length: 5 }, (_element, index) => (
          <input
            key={index}
            onChange={() => this.onSelectedChange(index)}
            type="checkbox"
            checked={checked[index] || false}
            disabled={!checked[index] && disabled}
          />
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
like image 150
Tholle Avatar answered Sep 19 '22 22:09

Tholle