Create a toggle switch in React
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
- How to add a loading spinner in React
- How to render curly braces as plain text in React
- How to add Emoji Picker in the React
- How to set up a proxy in React App
Demo Application
Output - Create a toggle switch in React - Clue Mediator
Steps to create a toggle switch in React
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..!! ๐