React Toggle Switch Component

I have spent some years building complex web applications, and if there is one UI element I get asked for constantly, it is the toggle switch.

Whether you are building a settings page for a SaaS platform or a dark mode trigger for a blog, a well-designed toggle switch is essential.

In this tutorial, I will show you exactly how to create a high-quality React toggle switch component that looks great and works perfectly.

Why Use a Toggle Switch Instead of a Checkbox?

In my experience, a checkbox is great for forms where you hit “Save” at the end.

However, a toggle switch is much better for settings that should take effect immediately, like turning on “High Speed Data” on a mobile plan.

It provides a much better user experience because it mimics a physical light switch that people already understand.

Method 1: Build a Custom Toggle Switch from Scratch

I always prefer building my own components first because it gives me total control over the styling and behavior.

This method uses a hidden checkbox for the logic and a styled span for the visual toggle.

The React Component Code

Here is the complete code for a functional toggle switch. I’ve used a “Notification Settings” example, which is common in US-based apps.

import React, { useState } from 'react';
import './ToggleSwitch.css';

const ToggleSwitch = () => {
  const [isOn, setIsOn] = useState(false);

  const handleToggle = () => {
    setIsOn(!isOn);
  };

  return (
    <div className="toggle-container">
      <h2>Email Notifications</h2>
      <p>Receive weekly updates on US Market Trends.</p>
      <div className="switch-wrapper">
        <label className="toggle-switch">
          <input 
            type="checkbox" 
            checked={isOn} 
            onChange={handleToggle} 
          />
          <span className="slider round"></span>
        </label>
        <span className="status-text">
          {isOn ? "Notifications: ON" : "Notifications: OFF"}
        </span>
      </div>
    </div>
  );
};

export default ToggleSwitch;

The CSS Styling

To make this look professional, you need specific CSS. This creates the smooth sliding animation we all expect.

/* ToggleSwitch.css */
.toggle-container {
  font-family: Arial, sans-serif;
  padding: 20px;
  max-width: 400px;
}

.switch-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
}

.toggle-switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.status-text {
  font-weight: bold;
  color: #333;
}

You can see the output in the screenshot below.

React Toggle Switch Component

I have found that using the transform property for the slider movement is better for performance than changing the left property.

Method 2: Create a Reusable Toggle Component

When I work on large-scale projects, I never hardcode my toggles. Instead, I create a reusable component that accepts props.

This allows you to use the same logic for “Dark Mode,” “Privacy Settings,” or “Auto-Renewal” options.

The Reusable Component Code

import React from 'react';
import './ReusableToggle.css';

const CustomToggle = ({ label, id, toggled, onChange }) => {
  return (
    <div className="custom-toggle-row">
      <label htmlFor={id} className="label-text">{label}</label>
      <div className="toggle-switch">
        <input
          id={id}
          type="checkbox"
          checked={toggled}
          onChange={(e) => onChange(e.target.checked)}
        />
        <span className="slider round" />
      </div>
    </div>
  );
};

// Example Usage in a Settings Page
const AppSettings = () => {
  const [darkMode, setDarkMode] = React.useState(false);
  const [autoRenew, setAutoRenew] = React.useState(true);

  return (
    <div className="settings-page">
      <h1>Account Settings</h1>
      <CustomToggle 
        id="dark-mode"
        label="Enable Dark Mode" 
        toggled={darkMode} 
        onChange={setDarkMode} 
      />
      <CustomToggle 
        id="auto-renew"
        label="Premium Membership Auto-Renewal" 
        toggled={autoRenew} 
        onChange={setAutoRenew} 
      />
    </div>
  );
};

export default AppSettings;

The CSS for Reusable Toggles

/* ReusableToggle.css */
.settings-page {
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.custom-toggle-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #ddd;
}

.label-text {
  font-size: 16px;
  color: #444;
}

/* Include the slider CSS from Method 1 here */

You can see the output in the screenshot below.

Toggle Switch React Component

In this setup, I use id and htmlFor to ensure the component is accessible for screen readers.

Method 3: Use a Library (React-Switch)

Sometimes, you don’t want to reinvent the wheel, especially when deadlines are tight.

In my professional work, if I need a highly polished toggle with complex animations, I often turn to libraries like react-switch.

How to Implement React-Switch

First, you need to install the package via npm: npm install react-switch

Then, you can implement it like this:

import React, { useState } from "react";
import Switch from "react-switch";

const SubscriptionManager = () => {
  const [checked, setChecked] = useState(false);

  const handleChange = (val) => {
    setChecked(val);
  };

  return (
    <div style={{ padding: "20px" }}>
      <h3>Sling TV Subscription</h3>
      <p>Toggle to activate your premium sports package.</p>
      <label>
        <span>{checked ? "Active" : "Inactive"}</span>
        <Switch 
          onChange={handleChange} 
          checked={checked} 
          onColor="#86d3ff"
          onHandleColor="#2693e6"
          handleDiameter={30}
          uncheckedIcon={false}
          checkedIcon={false}
          boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
          activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
          height={20}
          width={48}
          className="react-switch"
          id="material-switch"
        />
      </label>
    </div>
  );
};

export default SubscriptionManager;

I like this library because it handles all the edge cases for touch devices and keyboard navigation automatically.

Handle Accessibility (Aria-Labels)

One mistake I see many junior developers make is forgetting about accessibility. If a user is using a screen reader, they need to know what the toggle does.

Always include aria-label or link the label correctly using htmlFor. This ensures your app is usable by everyone, including those with visual impairments.

Common Issues and Performance Tips

When building these, I’ve noticed that if you have a list of 100 toggles, your app might slow down.

To fix this, make sure your toggle component is memoized using React.memo if it doesn’t need to re-render constantly.

Also, always ensure your onChange function is properly passed down to avoid unnecessary state updates.

Creating a toggle switch in React is an easy task, but the details make a big difference in the final product.

I hope this guide helps you build better interfaces for your users. Whether you build it from scratch or use a library, focus on the user experience.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.