How to Create a Toggle/Switch Button in ReactJS: Step-by-Step Guide with Working Example

How to Create a Toggle:Switch Button in ReactJS

If you want to create a toggle or switch button in ReactJS, the simplest approach is to store an on or off value in state and flip it when the user clicks a button.

In practice, that means three parts:

  • a state variable with useState
  • a click handler that changes the state
  • conditional styles that show whether the switch is on or off

Below is a working example you can use in a basic React app.

What is a toggle switch in React?

A toggle switch is a UI control that lets users switch between two states, usually on and offenabled and disabled, or true and false.

In React, a toggle switch is usually built as a component that:

  • reads a boolean value from state
  • updates that value on click
  • changes its label or visual style based on the current state

You will see this pattern in dark mode settings, notification preferences, privacy controls, and feature flags.

How the React toggle works

The logic is small, but it helps to be precise.

  1. Create a boolean state value with useState(false).
  2. Add a function that flips the state.
  3. Change the button text and class name based on the current value.

The most reliable way to flip the state is this:

setIsOn((currentValue) => !currentValue);

That functional update matters because it avoids bugs when React batches updates. It is a better default than writing setIsOn(!isOn) in reusable UI components.

Working React toggle switch example

Here is a simple reusable toggle switch component. Create a file ToggleSwitch.jsx and paste the exact code.

import { useState } from "react";
import "./ToggleSwitch.css";

export default function ToggleSwitch({
  label = "Email notifications",
  defaultOn = false,
  onToggle,
}) {
  const [isOn, setIsOn] = useState(defaultOn);

  function handleToggle() {
    setIsOn((currentValue) => {
      const nextValue = !currentValue;

      if (onToggle) {
        onToggle(nextValue);
      }

      return nextValue;
    });
  }

  return (
    <div className="toggle-wrapper">
      <span className="toggle-label">{label}</span>

      <button
        type="button"
        className={`toggle-switch ${isOn ? "on" : "off"}`}
        aria-pressed={isOn}
        aria-label={label}
        onClick={handleToggle}
      >
        <span className="toggle-thumb" />
        <span className="toggle-text">{isOn ? "On" : "Off"}</span>
      </button>
    </div>
  );
}

This component works because:

  • isOn stores the current switch state
  • handleToggle flips the state safely
  • className changes between on and off
  • aria-pressed exposes the state to assistive technology
  • aria-label gives the button a clear accessible name
  • type="button" prevents accidental form submission

Add CSS styling for the switch

The JavaScript handles behavior. The CSS makes it look like a switch. Create the ToggleSwitch.css file and paste the exact CSS.

.toggle-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  font-family: Arial, sans-serif;
}

.toggle-label {
  font-size: 16px;
  color: #1f2937;
}

.toggle-switch {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  width: 78px;
  height: 40px;
  padding: 4px 10px;
  border: none;
  border-radius: 999px;
  cursor: pointer;
  transition: background-color 0.25s ease;
  color: #ffffff;
}

.toggle-switch.on {
  background-color: #16a34a;
}

.toggle-switch.off {
  background-color: #6b7280;
}

.toggle-thumb {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #ffffff;
  transition: transform 0.25s ease;
}

.toggle-switch.on .toggle-thumb {
  transform: translateX(38px);
}

.toggle-text {
  position: relative;
  z-index: 1;
  width: 100%;
  text-align: center;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: 0.02em;
}

This style keeps the component simple enough for beginners while still looking like a modern switch.

How to use the toggle component in a parent component

Now use the component inside your app.

import ToggleSwitch from "./ToggleSwitch";

export default function App() {
  function handleNotificationsChange(isEnabled) {
    console.log("Notifications enabled:", isEnabled);
  }

  return (
    <main style={{ padding: "40px" }}>
      <h1>React Toggle Switch Example</h1>

      <ToggleSwitch
        label="Email notifications"
        defaultOn={true}
        onToggle={handleNotificationsChange}
      />
    </main>
  );
}

If you place ToggleSwitch.jsxToggleSwitch.css, and App.jsx in the right locations in a standard React project, this example will run correctly.

Why this code works correctly

A lot of quick tutorials leave small problems behind. This one avoids the common ones.

1. It uses a functional state update

This line:

setIsOn((currentValue) => {
  const nextValue = !currentValue;
  return nextValue;
});

is safer than directly negating a possibly stale value.

2. It uses a real button

Some examples use a plain div with an onClick handler. That is weak accessibility. A button already supports keyboard interaction and conveys the right meaning.

3. It avoids form bugs

type="button" matters. Without it, a button inside a form becomes a submit button by default.

4. It keeps logic and styling separate

The component handles state and events. The CSS handles the appearance. That makes the code easier to maintain.

How to make the switch accessible

If you are building a custom React switch, accessibility is not optional.

Use these rules:

  • Prefer a button or a properly implemented checkbox-based control
  • Add an accessible label
  • Expose the current pressed state with aria-pressed for toggle buttons
  • Make sure the switch can be used with a keyboard
  • Keep the contrast strong enough for the on and off states

In the example above:

  • the button has an accessible name through aria-label
  • the state is exposed with aria-pressed
  • keyboard interaction comes from the native button element

For many settings interfaces, this is a clean and practical solution.

Common mistakes when building a React switch button

Using setIsOn(!isOn) everywhere

This often works in simple demos, but the functional form is a better habit in components that may update quickly or be reused.

Using a div instead of a button

That usually creates an accessibility problem and forces you to rebuild keyboard behavior manually.

Forgetting to lift state when needed

If the parent component needs to know whether the switch is on, pass a callback like onToggle. Otherwise, the toggle state stays trapped inside the child component.

Overcomplicating the component

You do not need reducers, custom hooks, or animation libraries for a basic switch. Start with a small component. Add complexity only when the product actually needs it.

Custom toggle vs UI library: which should you use?

If you only need one or two simple switches, a custom component like this is usually enough. It is lightweight, easy to style, and easy to understand.

A UI library makes more sense when:

  • your app already uses one
  • you need design consistency across many controls
  • you need advanced accessibility patterns out of the box
  • your team wants standardized components instead of one-off CSS

For a beginner tutorial, writing the switch yourself is useful because it teaches state, event handling, and conditional styling in one small example.

FAQ

How do you create a toggle button in ReactJS?

Create a boolean state value with useState, then flip it inside a click handler and update the UI based on the current value.

Should a React toggle switch use useState?

Yes, in most simple cases. useState is the standard way to manage a local on/off state in a functional React component.

Is a toggle switch better than a checkbox in React?

It depends on the interface. A switch usually fits immediate on/off settings. A checkbox is often better inside forms with multiple selections.

How do you style a custom switch in React?

The usual approach is to apply one class for the on state and another for the off state, then animate the thumb with CSS transitions.

Conclusion

To create a toggle or switch button in ReactJS, keep the structure simple: store a boolean in state, flip it with a click handler, and change the styles based on the current value.

The example in this guide is small on purpose. It is easy to copy, easy to debug, and flexible enough to reuse in settings panels, feature toggles, and preference forms.