0

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.