Search code examples
javascriptreactjsreact-bootstrap

Set default value to react boostrap Form.Check


I have the following code for the checkbox:

<Form.Group  controlId="formBasicCheckbox">
       <Form.Check
             onChange={(disabled)=> {disabled ? packed = 'yes' : packed = 'no'}} >
       </Form.Check>
</Form.Group>

Also I need to set default value to it but can't find a way to do that. I tried 'value', 'defaultValue', but nothing helps and google neither.


Solution

  • defaultValue does work but take note that this is primarily for uncontrolled components. Since you have an onChange I think what you want is value instead (unless the onChange is to for another purpose - regardless I have code below that can help).

    If it helps you can also use defaultChecked prop which accepts a boolean that will set if the checkbox should initially be checked or not (you can also use checked prop - but at that point you need to control its value via, for example, state).

    In addition, I think you are misunderstanding the onChange prop. Its callback argument is a SyntheticEvent - I find that disabled is an odd identifier for that and confusing. See code below for insight

    const [packed, setPacked] = React.useState("yes");
    
    <Form.Check
      defaultChecked={true} // if checkbox should be checked by default
      // defaultValue="yes" // use this instead of value if you want uncontrolled component
      value={packed} // state-controlled value of checkbox
      onChange={(e) => {
        // e.target.checked will return true or false if checkbox is checked
        e.target.checked ? setPacked("yes") : setPacked("no");
      }}
    ></Form.Check>
    

    Edit pedantic-cori-cf2ed