Search code examples
javascriptreactjsantd

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

  • 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.