How do I react to a checkbox that selects all the other checkboxes?

1

I'm making a list of checkboxes and for that I based on this page link , I found it very useful. But now I need to add another checkbox that I select to all the previous ones. How would you do it based on what's on the page? But, could you tell me another way to make that list of checkboxes and that additional checkbox that checks or disengages all the previous ones in react (the same would prefer the one of the page).

    
asked by JLeOne 01.10.2017 в 23:50
source

1 answer

0

Simple. First you must always bear in mind that in React you work with controlled elements , that is, elements that will be controlled by the React status to change and / or mutate. That said, it's really simple.

Have in your state Boolean values for each checkbox (true | false). Now, for each checkbox you must assign the same event, say onCheck and pass it as a parameter, the name of the checkbox . Within this method you update the status by changing the value true or false for that checkbox and at the same time, putting the rest of the checkboxes as false .

Example

class CheckBoxExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkboxes: {
        c1: false,
        c2: false,
        c3: false,
        selected: null,
      },
    };
  }
 
  onCheck(name, val) {
    const checkboxes = Object.assign({},this.state.checkboxes, {});
    for (let key in checkboxes) {
      checkboxes[key] = false;
    }
    checkboxes[name] = true;
    checkboxes.selected = val;
    this.setState({ checkboxes });
  }
  
  render() {
    return (
      <div>
        <label>Seleccionado: {this.state.checkboxes.selected}</label><br />
        C1 <input 
             type="checkbox" 
             value="c1"
             checked={this.state.checkboxes.c1} 
             onChange={(e) => this.onCheck('c1', e.target.value) }
           />
        C2 <input 
             type="checkbox" 
             value="c2"
             checked={this.state.checkboxes.c2} 
             onChange={(e) => this.onCheck('c2', e.target.value) }
           />
        C3 <input 
             type="checkbox" 
             value="c3"
             checked={this.state.checkboxes.c3} 
             onChange={(e) => this.onCheck('c3', e.target.value) }
           />
      </div>
    );
  }
}

const node = document.getElementById('root');
ReactDOM.render(<CheckBoxExample />, node);
<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>
    
answered by 05.10.2017 в 17:15