Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

classAppextendsReact.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) => (
          <inputkey={index}onChange={() => this.onSelectedChange(index)}
            type="checkbox"
            checked={checked[index] || false}
            disabled={!checked[index] && disabled}
          />
        ))}
      </div>
    );
  }
}

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

Solution 2:

with bootstrap it's only this

                <input
                    type="checkbox"
                    className="form-check-input"id="exampleCheck1"
                    disabled={true}
                />

Post a Comment for "Conditionally Disabled React Checkboxes"