React v.18 & React-Bootstrap v.5.0 - Toggle switch with dynamic checked unchecked attribute

89 views Asked by At

Library: React v.18.0

CSS: React-bootstrap v.5.0 framework

Component: Toggle switch

Official toggle switch documentation: https://react-bootstrap.github.io/docs/forms/checks-radios/#switches

Requirement: To have one switch with dynamic checked and unchecked attribute in the <Form.Check using let or useState hook.

Try 1: Used if...else expression in return statement to toggle the checked and unchecked attribute.

Try 2: Took the <Form.Check to a different function and did an if else with 2 separate <Form.check one with checked attribute another with unchecked attribute.

Coder view: https://stackblitz.com/edit/react-ug9ffy?file=src%2FApp.js

User view: https://react-ug9ffy.stackblitz.io

2

There are 2 answers

1
Caio Henrique On

You can use a Boolean value in the checked attribute:

export default function App() {
  const [check, setCheck] = useState(false)

  function verifyCheck() {
    if(check) {
      setCheck(false)
    } else {
      setCheck(true)
    }
  }

  return (
    <Form>
      <Form.Check // prettier-ignore
        checked={check}
        type="switch"
        id="custom-switch"
        label="Bill gates"
        onClick={verifyCheck}
      />
      <Form.Check // prettier-ignore
        checked
        disabled
        type="switch"
        label="Steve Jobs"
        id="disabled-custom-switch"
      />
    </Form>
  );
}
2
Takkie253 On

So I think you want a variable amount of checkboxes. To do this and to control the states of it, you should make an external component for a checkbox.

Something like this:

export default function App() {

//get data from api somewhere and set it in a state

  return (
    <Form>
        {yourCheckboxesFromAPI.map((item) => (<CheckBox data={item} />))}
    </Form>
  );
}


export default function CheckBox(item){
const [check, setCheck] = useState(false)

return (
    <Form.Check
        checked={check}
        disabled
        type="switch"
        label={item.label} //steve-jobs
        id="disabled-custom-switch"
        onClick={() => setChecked(!checked)}
    />
);
}