Now that we know what needs to go into the HTML, all we need to do is convert the HTML into a React component. Let’s start with a basic component here. We’ll make this a class component, and then we’ll convert it into hooks, as it’s easier for new developers to follow state than useState when building a React switch button.
Add the following to src/ToggleSwitch/ToggleSwitch.js file we created in the step 1.
At this point, it’s not possible to have multiple toggle switch sliders on the same view or page due to the repetition of ids. Although we could leverage React’s way of componentization here, we’ll be using props to dynamically populate the values:
The this.props.Name will populate the values of id, name and for (note that it is htmlFor in React JS) dynamically, so that you can pass different values to the component and have multiple instances on the same page.
You can test this component by updating the App.js with the below code.
Inspect the output at http://localhost:3000/ (possibly using your browser’s dev tools) and ensure everything is working correctly.
Now for the styling. This is a rough outline of what we’re after for the styling of our React switch button.
And this is what that looks like in SCSS. Add the following to src/ToggleSwitch/ToggleSwitch.scss:
Also, take a while to go through the code above. If there’s anything you’re unsure about, you can consult the Sass documentation , or ask a question at the SitePoint Forums .
To make the component more flexible, we can grab these dynamically from the control using HTML5 data-attributes :
We’ll hardcode the data attributes for testing but will make this more flexible in the final version:
Also, using a smaller version of the switch component React without the text for smaller screens would be a great idea. So let’s add the styling for it with some minimal sizes and remove the text:
With respect to responsiveness, we should be changing the complete size, so let’s use the CSS scale function. Here we’ve covered all the Bootstrap-based responsive widths of devices.
element in ToggleSwitch.js:
import React, { Component } from "react";
class ToggleSwitch extends Component {
render() {
return (
<div className="toggle-switch">
<input
type="checkbox"
className="toggle-switch-checkbox"
name="toggleSwitch"
/>
<label className="toggle-switch-label" htmlFor="toggleSwitch">
<span className="toggle-switch-inner" />
<span className="toggle-switch-switch" />
</label>
</div>
);
}
}
export default ToggleSwitch; Copy after login
Head back to the dev server and test your changes. If you’d like to check what you have against the finished SCSS file, you can find that here .
Step 6 – Theming in SCSS
Since we can use variables in SCSS, it is easier to add support for multiple color themes. You can read more about this in “Sass Theming: The Never Ending Story ”. We’ll use some color themes here and change all the raw colors to variables. The first three lines are a configurable set of colors, which helps us theme our little control:
create-react-app toggleswitch Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
And that’s it with the styling. Now let’s add some interactivity.
Step 7 – Interactions and JavaScript
Please note that the following section only contains demo code to explain the concepts. You should not be updating your actual ToggleSwitch component in this section.
Our basic component will be a dumb component (or presentation component) whose state will be controlled by a parent component or container, such as a form. What do we mean by controlled? Well, let’s look at an uncontrolled version first:
mkdir src/ToggleSwitch
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
When users interact with the above checkbox input, it will toggle between a checked and unchecked state of its own accord without us having to write any JavaScript. HTML input elements can manage their own internal state by updating the DOM directly.
However, in React, it’s recommended we use controlled components , as shown in the following example:
touch ToggleSwitch.js ToggleSwitch.scss Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Here, React is controlling the state of the checkbox input. All interactions with this input have to go through the virtual DOM. If you try to interact with the component as it is, nothing will happen, as we haven’t defined any JavaScript code that can change the value of the checked prop we’re passing in.
To fix this, we can pass in an onChange prop — a function to be called whenever the checkbox is clicked:
import React from 'react';
import ToggleSwitch from './ToggleSwitch/ToggleSwitch'
function App() {
return (
<ToggleSwitch />
);
}
export default App; Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Now, the checkbox input is interactive. Users can toggle the component “on” and “off” just like before. The only difference here is that the state is controlled by React, as opposed to the earlier uncontrolled version. This allows us to easily access the state of our component at any given time via JavaScript. We can also easily define the initial value when declaring the component.
Now, let’s look at how we can use this in the ToggleSwitch component. Below is a simplified class-based example:
<input type="checkbox" name="name" /> Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Now let’s convert the class-based component into a functional component using hooks:
<div >
<input type="checkbox" name="toggleSwitch" />
<label for="toggleSwitch">
Toggle Me!
</label>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
As you can see, we drastically reduced the number of lines using functional components and the hooks creation method.
If React Hooks are new to you, “React Hooks: How to Get Started & Build Your Own ”.
Step 8 – Finalizing the ToggleSwitch Component
Now, let’s get back to our ToggleSwitch component. We’ll need the following props:
When the small version is not used, the following optionLabels text will be used as default:
create-react-app toggleswitch Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Since most of the props have to be set by the user, and we can’t use arbitrary values, it’s always better to stop rendering if the required props aren’t passed in. This can be done using a simple JavaScript if statement or a ternary operator using ? : or a short-circuited &&:
mkdir src/ToggleSwitch
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
As our app grows, we can catch many bugs by type-checking. React has some built-in type-checking abilities. To run type checking on the props for a component, you can assign the special propTypes property. We can enforce the above list of props using React’s PropType library, a separate library that exports a range of validators that can be used to ensure the data you receive is valid.
You can install it like so:
touch ToggleSwitch.js ToggleSwitch.scss Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Then, import the PropTypes library using:
import React from 'react';
import ToggleSwitch from './ToggleSwitch/ToggleSwitch'
function App() {
return (
<ToggleSwitch />
);
}
export default App; Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
We’ll define the PropTypes in the following way:
<input type="checkbox" name="name" /> Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
By way of explanation:
PropTypes.string.isRequired: This is a string value, and it’s required and mandatory.
PropTypes.string: This is a string value, but it isn’t mandatory.
PropTypes.func: This prop takes in a function as a value, but it isn’t mandatory.
PropTypes.bool: This is a boolean value, but it isn’t mandatory.
PropTypes.array: This is an array value, but it isn’t mandatory.
Now, we can carry on with the ToggleSwitch component. Replace the contents of src/ToggleSwitch/ToggleSwitch.js with the following:
<div >
<input type="checkbox" name="toggleSwitch" />
<label for="toggleSwitch">
Toggle Me!
</label>
</div>
Copy after login
Copy after login
Copy after login
Copy after login
Finally, to test the component, update the App.js with the below code:
create-react-app toggleswitch Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Now, when you head to http://localhost:3000/ , you should see the working toggle.
Working Toggle Button
Step 9 – Making the Component Keyboard Accessible
The final step is to make our component keyboard accessible. To do this, first, alter the label like below:
mkdir src/ToggleSwitch
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
As you can see, we’ve added a tabIndex property, which we’re setting to 1 (focusable) or -1 (not focusable), depending on whether the component is currently disabled.
We’ve also declared a handleKeyPress function to deal with it receiving keyboard input:
touch ToggleSwitch.js ToggleSwitch.scss Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
This checks if the key pressed is the space bar. If so, it prevents the browser’s default action (scroll the page in this case) and toggles the component’s state.
And that’s essentially all you need. The component is now keyboard accessible.
However, there’s a slight problem. If you click the ToggleSwitch component, you will get an outline of the entire component, which is probably not desired. To combat this, we can alter things slightly to make sure it receives an outline when it’s focused on the keyboard, but not when it’s clicked:
import React from 'react';
import ToggleSwitch from './ToggleSwitch/ToggleSwitch'
function App() {
return (
<ToggleSwitch />
);
}
export default App; Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Here, we’ve added a tabIndex property to both inner elements to ensure they can’t receive focus.
Then, update the ToggleSwitch.scss file with the below code to apply a style to the ToggleSwitch’s inner element when it’s focused on the keyboard but not when it’s clicked.
<input type="checkbox" name="name" /> Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
You can read more about this technique here . It’s slightly hacky and should be dropped in favor of using :focus-visible , as soon as that gains wide enough browser support.
When you run the application, you should be able to toggle the component using the space bar.
Keyboard Accessible Toggle
A More Complete Example
To finish off, I’d like to demonstrate a more complete example of using the ToggleSwitch component in the following CodeSandbox.
This demo uses multiple ToggleSwitch components on the same page. The state of the last three toggles depends on the state of the first. That is, you need to accept marketing emails before you can refine your choice of which ones to receive.
Summary
In this article, I’ve shown how to create a reusable, iOS-inspired React toggle component using React. We looked at styling the component with SCSS, making it a controlled component, customizing it by passing it props, and making it keyboard accessible.
You can find the complete code for the React toggle component on our GitHub repo .
FAQs on How to Create a Toggle Switch in React as a Reusable Component
How Can I Customize the Appearance of My React Toggle Switch?
Customizing the appearance of your React toggle switch is quite straightforward. You can modify the CSS properties to suit your design needs. For instance, you can change the switch’s background color, border color, size, and shape. You can also add animations or transitions for a more interactive user experience. Remember to keep your changes consistent with your overall application design for a seamless user experience.
Can I Use the Switch Button React Component with Functional Components?
Yes, you can use the React toggle switch with functional components. The process is similar to using it with class components. You just need to import and use the switch component in your functional component. You can also use hooks like useState to manage the state of the switch.
How Can I Make My Switch Button React Component Accessible?
Accessibility is a crucial aspect of web development. To make your React toggle switch accessible, you can use ARIA (Accessible Rich Internet Applications) attributes. For instance, you can use the “aria-checked” attribute to indicate the state of the switch. You can also add keyboard support to allow users to toggle the switch using the keyboard.
How Can I Test My React Switch Component?
Testing is an essential part of the development process. You can use testing libraries like Jest and React Testing Library to test your react switch component. You can write tests to check if the switch toggles and renders correctly when clicked and handles props correctly.
Can I Use the React Toggle Switch with Redux?
Yes, you can use the React toggle switch with Redux. You can manage the state of the switch using Redux actions and reducers. This can be particularly useful if the state of the switch needs to be shared across multiple components or if it affects the global state of your application.
How Can I Add a Label to My React Toggle Switch?
Adding a label to your React toggle switch can improve its usability. You can add a label by wrapping the react switch component in a “label” element. You can also use the “htmlFor” attribute to associate the label with the switch.
How Can I Handle Errors in My React Toggle Switch Component?
Error handling is an important part of any component. In your React toggle switch component, you can use try-catch blocks to handle errors. You can also use error boundaries, a React feature that catches and handles errors in components.
Can I Use the React Toggle Switch in a Form?
Yes, you can use the React toggle switch in a form. You can handle the state of the switch in the form’s state. You can also handle the form submission and use the state of the switch to perform certain actions.
How Can I Animate My React Toggle Switch?
Animating your React toggle switch can enhance the user experience. You can use CSS transitions or animations to animate the switch, or you can use libraries like React Spring for more complex animations.
Can I Use the React Toggle Switch with TypeScript?
Yes, you can use the React toggle switch with TypeScript. You just need to define the props’ types and the switch’s state. This can help you catch errors during development and make your code more robust and maintainable.
How Can I Optimize the Performance of Switch Toggles?
You can optimize the performance of your React toggle switch by using React’s memo function to prevent unnecessary re-renders.
How Can I Handle State Management for Multiple Toggle Switches in a Single Form?
You can manage the state of multiple toggle switches in a single form by using an object to store each switch’s state. This allows you to easily update and access the state of each switch, making your form handling more efficient.