In this article, we are going to show you how to create a toggle switch in react using css.
Let’s begin by creating a Toggle component in react:
- The Toggle component has an input element with the type “checkbox”. We also give it an id so we can associate it with the label below.
- The label takes in a htmlFor attribute which corresponds to the id of the checkbox.
- Clicking on the label will also toggle the checkbox because of htmlFor
For the css style we will hide the checkbox. We still keep it in the DOM since we can use it in the css to check its state (on/off) using the :checked selector:
The .Toggle class styles the label, and the .Circle class styles the span:
The .Circle class is made round by keeping the width, height and border-radius the same size. The transition attribute will animate the change in position when we switch css classes.
And the most important part is the style below. When the hidden .CheckBox is checked (on) css will look from the next html tag in DOM with the .Circle class and style it as below. This style will move the circle to the right, using `left` attribute:
When the .CheckBox is not checked, css will simply use the .Circle class and this will trigger the transition attribute to animate the change.
We have it working 🎉
For the full code checkout our github page.