Naveen N
Naveen N

Reputation: 29

How to select only one checkbox in a group using reactjs component

I have multiple category each category contains multiple checkbox, for which I want only 1 checkbox to be checked in every category at a time using React js. This is what i want

onlyOne(event) {
    console.log("==",event.target.value)
    var checkboxes = document.getElementsByName('check')
    console.log("cheek",checkboxes);
    checkboxes.forEach((item) => {
      if (item !== event.target.name) item.checked = false
    })

}

HTML:

       <div>
        <label>RBA CONFIGURATION SCREEN </label><br/>               
        View  <input type="checkbox" name="check" value="0" onClick={this.onlyOne.bind(this)} checked=''/>
        Manage  <input type="checkbox" name="check" value="1" onClick={this.onlyOne.bind(this)} checked='' />
        Edit  <input type="checkbox" name="check" value="2" onClick={this.onlyOne.bind(this)} checked='' />
        </div>

Looking something like this in Reactjs https://stackoverflow.com/a/37002762

Radio button can't be used because the user should be able to un-check the selection

Upvotes: 0

Views: 5845

Answers (1)

primetwig
primetwig

Reputation: 465

I suggest switching to radio for your case.

Answer to your question:

// amount of checkboxes
const n = 3;

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      // checked/unchecked is stored here
      // initially the first one is checked:
      // [true, false, false]
      checkboxes: new Array(n).fill().map((_, i) => !i),
    };
  }
  onChange(e, changedIndex) {
    // it is a good habit to extract things from event variable
    const { checked } = e.target;
    
    this.setState(state => ({
      // this lets you unselect all.
      // but selected can be anly one at a time
      checkboxes: state.checkboxes.map((_, i) => i === changedIndex ? checked : false),
    }));
  }
  render() {
    const { checkboxes } = this.state;
    
    return (
      <div>
        {checkboxes.map((item, i) => (
          <input
            key={i}
            type="checkbox"
            checked={item}
            onChange={e => this.onChange(e, i) /* notice passing an index. we will use it */}
          />
        ))}
      </div>
    );
  }
}

ReactDOM.render(<Example />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 3

Related Questions