#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop - $20

Build a custom React toggle switch component

Last modified November 17th 2020 | #react | GitHub Source Code [GitHub]

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/src

Next create the JavaScript & CSS files for the component:

mkdir components cd components touch ToggleSwitch.js ToggleSwitch.css
Code language: CSS (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;
Code language: JavaScript (javascript)

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

As checkboxes have limited styling capabilities we will instead be styling the <span> element and hiding the checkbox itself. 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; }
Code language: CSS (css)

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;
Code language: JavaScript (javascript)

Now you have a flexible toggle switch component to use in your React projects. If this was you first time using the useState Hook I’d suggest reading the official documentation to learn more.

Related Posts