How To Create A Toggle Switch In React

Introduction

This article demonstrates how to create toggle switch using reactjs.

Prerequisites

  • Basic knowledge of ReactJS
  • Visual Studio Code
  • Node and NPM installed

Toggle Switch in React

To achieve this we need to install a package 'react-switch' to render the toggle switch in react and can import it and use it in our sample project.

Step 1. Create a React.js Project

Let's create a new React project by using the following command.

npx create-react-app toggle-switch-app

Step 2. Install NPM dependencies

npm i react-switch

Step 3. Create a Component for toggle switch

Create a folder for toggle switch and inside it create a component, 'toggleSwitch.js'. Add the following code to this component.

import React, { useState } from 'react';
import ReactSwitch from 'react-switch';

function ToggleSwitch() {
  const [checked, setChecked] = useState(true);

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

  return (
    <div className="app" style={{textAlign: "center"}}>
      <h4>Toggle switch in React</h4>
      <ReactSwitch
        checked={checked}
        onChange={handleChange}
      />
    </div>
  );
}

export default ToggleSwitch;

Step 4. Add the below code in App.js file

import './App.css';
import ToggleSwitch from './toggle-switch/toggleSwitch';

function App() {
  return (
    <ToggleSwitch/>
  );
}

export default App;

Step 5. Output

Now, run the project by using the 'npm start' command, and check the result.

toggle switch in React

Summary

In this article, I discussed how we can create a toggle switch feature in reactjs.