[MB]

Build a custom React toggle switch component

Last modified on October 27th 2020 GitHub [Source]

In this tutorial we’ll be building a custom React toggle switch component. Toggle switches allow users to make a selection between two opposing states. They’re commonly used to toggle settings in apps or selecting between two options in forms.

Here’s how the toggle switch will look and function once complete:

React Toggle Switch Component

Let’s get started by setting up the project using Create React App:

npx create-react-app react-toggle cd react-toggle

Now create the JavaScript & CSS files for the component:

mkdir components cd components touch ToggleSwitch.js ToggleSwitch.css

Open ToggleSwitch.js and add the following:

import React, { useState } from "react"; import "./ToggleSwitch.css"; function ToggleSwitch() { const [isToggled, setIsToggled] = useState(false); const onToggle = () => setIsToggled(!isToggled); return ( <label className="toggle-switch"> <input type="checkbox" checked={isToggled} onChange={onToggle} /> <span className="switch" /> </label> ); } export default ToggleSwitch;

Here we’re storing the state of the checkbox (isToggled) using the React State Hook. When the onChange event is triggered we then update using setIsToggled.

As checkboxes have limited styling capabilities we will instead be styling the <span> element and hiding the checkbox. Add the following CSS to ToggleSwitch.css:

.toggle-switch { position: relative; display: inline-block; width: 50px; height: 25px; } .toggle-switch input[type="checkbox"] { display: none; } .toggle-switch .switch { position: absolute; cursor: pointer; background-color: #ccc; border-radius: 25px; top: 0; right: 0; bottom: 0; left: 0; transition: background-color 0.2s ease; } .toggle-switch .switch::before { position: absolute; content: ""; left: 2px; top: 2px; width: 21px; height: 21px; background-color: #aaa; border-radius: 50%; transition: transform 0.3s ease; } .toggle-switch input[type="checkbox"]:checked + .switch::before { transform: translateX(25px); background-color: #6699cc; } .toggle-switch input[type="checkbox"]:checked + .switch { background-color: #336699; }

Finally let’s add the component to our application in the App.js file:

import React from "react"; import ToggleSwitch from "./components/ToggleSwitch"; function App() { return ( <> <ToggleSwitch /> </> ); } export default App;

Now you have a flexible toggle switch component to use in React projects.