Hello Sunil
build-custom-toggle-switch-in-react-featured-image

How to Build a Custom Toggle Switch in React with Styled-Components

In modern web development, enhancing user experience with custom and intuitive UI elements is key. One such element is a toggle switch, commonly used for features like dark mode or enabling/disabling functionality.

In this blog, we’ll explore how to create a custom toggle switch in React using styled-components for dynamic styling.

We’ll walk through a simple toggle switch component that changes its appearance based on the isOn state. This switch is fully customizable and can be easily adapted to any project.

Start by creating a ToggleSwitch.jsx file and importing the necessary libraries. The useState hook will help manage the toggle’s state, while styled-components will allow us to define the styles directly within our component.

import React, { useState } from "react";
import styled from "styled-components";

Next, we’ll define the structure of the toggle. The toggle switch has two main parts:

  • The Switch container: This is the outer box that holds the switch.
  • The Slider: This is the actual switch that slides from left to right when toggled.

Here’s how we structure the component:

const Switch = styled.div`
  position: relative;
  display: inline-block;
  width: 48px;
  height: 22px;
`;

const Slider = styled.div`
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: ${(props) => (props.isOn ? "#d5f1ff" : "#ffffff")};
  transition: 0.4s;
  border-radius: 34px;
  border: 1px solid #beb6b4;

  &::before {
    position: absolute;
    content: "";
    height: 15px;
    width: 15px;
    left: ${(props) => (props.isOn ? "26px" : "4px")};
    bottom: 3px;
    background-color: #b9b9b9;
    transition: 0.4s;
    border-radius: 50%;
  }
`;

We’ll use the useState hook to manage the isOn state, which will track whether the switch is toggled on or off. A handleToggle function will update this state when the user clicks on the switch.

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

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

  return (
    <div>
      <Switch onClick={handleToggle}>
        <Slider isOn={isOn} />
      </Switch>
    </div>
  );
};
  • Dynamic Background Color: The Slider component’s background color changes based on the isOn state. If isOn is true, it applies a light blue color (#d5f1ff), indicating the switch is active.
  • Slider Movement: The ::before pseudo-element within the Slider is the round knob that slides. The left property controls its position. When isOn is true, the knob moves to the right (26px), otherwise, it stays to the left (4px).
  • Smooth Transition: The transition: 0.4s ensures a smooth animation when the switch toggles, making it more visually appealing.

Here’s the full code for our toggle switch component:

ToggleSwitch.jsx

import React, { useState } from "react";
import styled from "styled-components";


const Switch = styled.div`
  position: relative;
  display: inline-block;
  width: 48px;
  height: 22px;
`;

const Slider = styled.div`
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: ${(props) => (props.isOn ? "#d5f1ff" : "#ffffff")};
  transition: 0.4s;
  border-radius: 34px;
  border: 1px solid #beb6b4;

  &::before {
    position: absolute;
    content: "";
    height: 15px;
    width: 15px;
    left: ${(props) => (props.isOn ? "26px" : "4px")};
    bottom: 3px;
    background-color: #b9b9b9;
    transition: 0.4s;
    border-radius: 50%;
  }
`;

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

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

  return (
    <div>
      <Switch onClick={handleToggle}>
        <Slider isOn={isOn} />
      </Switch>
    </div>
  );
};

export default ToggleSwitch;

Output:

custom-toggle-switch-component

This toggle switch component is a great example of how to create interactive, dynamic UI elements using React and styled-components. You can easily modify the colors, dimensions, and animations to fit your project’s design requirements.

With styled-components, you can keep your styles clean, modular, and maintainable directly within your component files.

Feel free to experiment and customize the toggle to suit your needs!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.