Search code examples
javascriptreactjsforms

How to set the "checked" value of a React switch to a reference in React Js?


  const passiveIncomeTaxable = useRef(false);

  <Modal.Body hidden={SimpleMode}>
    <Form.Check
         type="switch"
        label="Is this income taxable?"
         name="income-passive"
           id="income-passive"
          ref={passiveIncomeTaxable}
     />
  </Modal.Body>

Everything here seems to be working just fine, but if I change the value of the switch and log the switch value to the console, it always returns on, even if the switch component is set to off.

I need to store the value of the switch component to a reference so that I could insert it into the database.


Solution

  • You can use state:

    const [isTaxable, setIsTaxable] = useState(false);
    
    <Form.Check
      type="switch"
      label="Is this income taxable?"
      name="income-passive"
      id="income-passive"
      checked={isTaxable}
      onChange={() => setIsTaxable(prev => !prev)}
    />
    

    Or, to make it uncontrolled:

    const passiveIncomeTaxable = useRef(false)
    
    <Form.Check
      type="switch"
      label="Is this income taxable?"
      name="income-passive"
      id="income-passive"
      onChange={() => {
        console.log(passiveIncomeTaxable.current.checked)
      }}
      ref={passiveIncomeTaxable}
    />