react bootstrap 5 toggle switch example

react bootstrap 5 toggle switch example

March 27, 2023 By Aaronn

In this tutorial, we will see toggle switch in react with bootstrap 5. We will see toggle switch checkbox component, toggle switch on off using react bootstrap 5.

Install & Setup Vite + React + Typescript + Bootstrap 5


React Bootstrap 5 Toggle Switch Example

1. Create simple react bootstrap toggle switch checkbox using react-bootstrap Form, Form.Check component.

import { Container } from "react-bootstrap";
import Form from "react-bootstrap/Form";

export default function SwitchExample() {
  return (
    <Container className="mt-5">
      <Form>
        <Form.Check
          type="switch"
          id="custom-switch"
          label="Check this switch"
        />
        <Form.Check
          disabled
          type="switch"
          label="disabled switch"
          id="disabled-custom-switch"
        />
      </Form>
    </Container>
  );
}
react bootstrap toggle switch

react bootstrap toggle switch

2. react bootstrap 5 toggle switch using usestate hook.

import { useState } from "react";
import { Form } from "react-bootstrap";

export default function ToggleSwitch() {
  const [isChecked, setIsChecked] = useState(false);

  const handleToggle = () => setIsChecked(!isChecked);

  return (
    <Form>
      <Form.Check
        type="switch"
        id="toggle-switch"
        label="Toggle"
        checked={isChecked}
        onChange={handleToggle}
      />
    </Form>
  );
}


3. react bootstrap 5 ON and OFF toggle switch.

import { useState } from "react";
import { Form } from "react-bootstrap";

export default function OnOffToggleInput() {
  const [isChecked, setIsChecked] = useState(false);

  const handleToggle = () => setIsChecked(!isChecked);

  return (
    <Form>
      <div className="d-flex align-items-center">
        <span className="me-2">{isChecked ? "On" : "Off"}</span>
        <Form.Check
          type="switch"
          id="toggle-switch"
          label=""
          checked={isChecked}
          onChange={handleToggle}
        />
      </div>
    </Form>
  );
}
react bootstrap 5 on and off toggle switch

react bootstrap 5 on and off toggle switch