Home > database >  Get a checkbox value on change of other checkbox in react
Get a checkbox value on change of other checkbox in react

Time:12-09

I have 2 checkboxes A and B. I want to check whether checkbox B is checked or not on change of checkbox A and vice versa. Also I want to change checkbox B on change of checkbox A. How can we achieve that in react.js.

CodePudding user response:

You can create a state for both of them and change it accordingly.
This way you'll have access to it whenever needed.

Also, to avoid handling changes separately for every input, you can give each of them a name and then have a single dedicated function that changes the value of the checkbox based on it's name.

Example:

function App() {
   const [state, setState] = useState({
      firstCheckbox: false,
      secondCheckbox: false,
   })

   const handleChange = (e) => {
      setState(prev => ({
         ...prev,
         [e.currentTarget.name]: e.currentTarget.checked,
      }));
   };

   return (
      <>
         <input
            name='firstCheckbox'
            type='checkbox'
            checked={state.firstCheckbox}
            onChange={handleChange}
         />

         <input
            name='secondCheckbox'
            type='checkbox'
            checked={state.secondCheckbox}
            onChange={handleChange}
         />
      </>
   )
}

Currently in this example, each checkbox relates to it's own state.
However, you can easily adjust the handleChange function based on your needs.

CodePudding user response:

HandleFirstCheckBox =(e)=>{
    this.setState({firstCheckBox : e.checked})
}

HandleSecondCheckBox =(e)=>{
this.setState({secondCheckBox : e.checked})
}

 



<input
    name='firstCheckbox'
    type='checkbox'
    value={this.state.firstCheckBox}
    onChange={this.HandleFirstCheckBox}
    onBlur={this.HandleSecondCheckBox}

 />
<input
    name='secondCheckbox'
    type='checkbox'
    value={this.state.secondCheckbox}
    onChange={this.HandleSecondCheckBox}
    onBlur ={this.HandleFirstCheckBox}
  />
  • Related