How to create a toggle switch using React.js

Vihanga Nivarthana
1 min readNov 19, 2020
preview

Many modern apps and websites are use toggle switches. Let’s see how to make a custom toggle switch.

To overcome this, we need to design the toggle switch’s layout first. to do this, we can use HTML checkbox and a label

here is the code example

in above code, I wrapped HTML checkbox and a div using a label and gave a class name to the label as “slider” and the other div named as “sort”

Next step is styling the layout using CSS

here is the sample CSS code sample

The layout part is now complete.

So how to detect the switch is on or off?

To detect the switch status, we can use “useState” hook comes with react.js and implement a new state called “isOn”.

then we can toggle the state using a function called “toggle” and implement it to the “onChange” event in the check box

Here is the Full JSX code

Final output

final output

--

--