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
Demo Application
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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import React, { useState } from 'react'; import ReactSwitch from 'react-switch'; function App() { const [checked, setChecked] = useState(true); const handleChange = val => { setChecked(val) } return ( <div className="app"> <h4>Toggle switch in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <ReactSwitch checked={checked} onChange={handleChange} /> <div style={{ marginTop: 10 }}>Value: {checked ? 'True' : 'False'}</div> </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..!! 🙂