Clue Mediator

Create a toggle switch in React

๐Ÿ“…January 11, 2022
๐Ÿ—ReactJS

Today we will show you how to create a toggle switch in React. Here we will use the NPM Package to create a toggle button in React.

Checkout more articles on ReactJS

Demo Application

Output - Create a toggle switch in React - Clue Mediator

Output - Create a toggle switch in React - Clue Mediator

Steps to create a toggle switch in React

  1. Install NPM package
  2. Add a toggle switch in component
  3. Output

1. Install NPM package

Here we will use the react-switch package to render the toggle switch in React. Run the following command to install the package.

npm i react-switch

2. Add a toggle switch in component

Letโ€™s import the `react-switch` at the top of the React component and render the element.

App.js

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

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

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

  return (
    <div class="app">
      <h4>Toggle switch in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
      <reactswitch checked onchange={handleChange}>
      <div 10="" style={{ margintop: }}>Value: {checked ? 'True' : 'False'}</div>
    </reactswitch></div>
  );
}

export default App;

In the above example, we have used the `checked` & `onChange` property to handle the selected value of the toggle switch. Here you may find more properties of the component.

3. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚

Demo & Source Code

GitHub Repository StackBlitz Project