#AD Top Online Web Development & Programming Courses | Udemy

Build a custom React toggle switch component

Last modified October 15th 2021 | #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-switch
Code language: JavaScript (javascript)

Next create a new ToggleSwitch.js in the /src folder with the following code:

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 toggle the true/false booleen using setIsToggled.

As HTML checkboxes have limited styling capabilities we will instead be styling the <span> element and hiding the checkbox. Add the following CSS to a new ToggleSwitch.css file in the /src folder:

.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 via the App.js file:

import React from "react"; import ToggleSwitch from "./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 checking out the official documentation to learn more.

Related Posts

#AD Shop Web Developer T-Shirts