Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a Switch in ReactJS?
ReactJS is a popular JavaScript library for building user interfaces, and it provides an effective approach to developing interactive components. Toggle switches are frequently used to allow users to switch between dark mode and light mode themes in web applications. Toggle switches can also be used to show or hide specific content or sections of a page. In this article, we will explore how to create a toggle switch using ReactJS.
Prerequisites
Before proceeding with this tutorial, it is assumed that you have a basic understanding of ReactJS and have a development environment set up with Node.js and npm installed.
Setting Up the React App
To begin, let's create a new React application using Create React App. Open your command prompt and run the following command:
npx create-react-app toggle-slider-switch
This command will create a new directory called toggle-slider-switch and set up a basic React application inside it. Navigate to the project directory with the following command:
cd toggle-slider-switch
Creating the ToggleSlider Component
In the src directory of your project, create a new file called ToggleSlider.js. This file will contain our toggle slider component code. The component uses React's useState hook to manage the switch state:
import React, { useState } from 'react';
import './ToggleSlider.css';
const ToggleSlider = () => {
const [checked, setChecked] = useState(false);
const handleToggle = () => {
setChecked(!checked);
};
return (
<div className="toggle-slider">
<input
type="checkbox"
id="toggle"
checked={checked}
onChange={handleToggle}
/>
<label htmlFor="toggle" className="slider" />
</div>
);
};
export default ToggleSlider;
In this code, we import the useState hook from React, which allows us to handle state in functional components. The ToggleSlider component maintains the state of the switch using the checked variable. The handleToggle function updates the state when the switch is clicked.
Styling the Toggle Slider
Create a new file called ToggleSlider.css in the same src directory. Add the following CSS code to style the toggle slider:
.toggle-slider {
position: relative;
width: 60px;
height: 34px;
}
.slider {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 34px;
cursor: pointer;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: '';
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
border-radius: 50%;
transition: 0.4s;
}
input[type='checkbox'] {
display: none;
}
input[type='checkbox']:checked + .slider {
background-color: #2196f3;
}
input[type='checkbox']:checked + .slider:before {
transform: translateX(26px);
}
This CSS code styles the toggle slider by hiding the default checkbox input and using a custom slider design. The :before pseudo-element creates the circular slider handle that moves when toggled.
Implementing the ToggleSlider Component
Next, modify the App.js file in the src directory to include the ToggleSlider component. Open App.js and update it with the following code:
import React from 'react';
import ToggleSlider from './ToggleSlider';
const App = () => {
return (
<div className="app">
<h1>Toggle Slider Example</h1>
<ToggleSlider />
</div>
);
};
export default App;
Here we import the ToggleSlider component and render it within the App component. This will display the toggle slider on the screen.
Running the React App
Now run the toggle switch app. In your command prompt, ensure you are in the project's root directory (toggle-slider-switch) and run:
npm start
After the compilation process, your default browser will open, and you should see the heading "Toggle Slider Example" along with the toggle slider on the screen.
Testing the Toggle Slider
Clicking the toggle slider will switch its state and change its appearance. The initial state is set to false, so when you click the slider, it will turn blue and slide to the right, indicating the true state. Click it again, and it will return to the initial gray state on the left.
Enhanced Switch with Labels
You can enhance the switch by adding labels to show the current state:
import React, { useState } from 'react';
import './ToggleSlider.css';
const EnhancedToggleSlider = () => {
const [checked, setChecked] = useState(false);
const handleToggle = () => {
setChecked(!checked);
};
return (
<div className="toggle-container">
<span>{checked ? 'ON' : 'OFF'}</span>
<div className="toggle-slider">
<input
type="checkbox"
id="enhanced-toggle"
checked={checked}
onChange={handleToggle}
/>
<label htmlFor="enhanced-toggle" className="slider" />
</div>
</div>
);
};
export default EnhancedToggleSlider;
Conclusion
In this article, we covered how to create a toggle switch in ReactJS using useState hook and CSS styling. The switch provides a clean, interactive way for users to toggle between states in your React applications.
