Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a checkbox value on change of other checkbox in react

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Example:

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

   const handleChange = (e) => {
      setState(prev => ({
         ...prev,
         [e.target.name]: e.target.value
      }))
   }

   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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading