Building toggle switch using React, TypeScript & Styled Components.
Beginners guide
A toggle switch is nothing but a UI component to indicate whether the value is true or false (can also display on/off).
Lets jump onto creating a custom react toggle switch component using typeScript and styled components.
Our final result will look something like this:
Step 1:
lets create the project named my-toggle-switch using npx-create-react-app since we will be using typescript remember to start Create React App project with TypeScript, so run on your terminal:
npx create-react-app my-toggle-switch --template typescript
Step 2:
Now install styled component using command below:
npm install --save @types/styled-components
Step 3:
Create functional component named ToggleSwitch.tsx which will look like this:
import styled from "styled-components";export default function ToggleSwitch(){
return (
<div>
<label>
toggle me:
<input type="checkbox"/>
</label>
</div>
);
}
Before moving forward lets talk about Controlled Components in React. (If you like to dive into code directly skip to step 4)
HTML Forms are peculiar in a way that they maintain their own state and gets updated based on user input (you must have used the form elements a lot like<input>
, <textarea>
, and <select>
), if you want to use this default form behavior in react it will work fine, but to keep track of the application state:
- We need our react component to not only render a form but to also control what happens in that form on subsequent user input.
- React controls the value of input form element this way and this technique is called “controlled components”.
- With a controlled component, the input’s value is always driven by the React state.
Lets move onto next steps:
Let’s use useState hook, it lets us keep local state in a function component.
Step 4:
Import useState hook and ChangeEvent from react.
import { useState, ChangeEvent } from "react";
import styled from "styled-components";
import COLORS from "./color";
Step 5:
// Creating ToggleSwitch.tsx moduleexport default function ToggleSwitch() {
const [switchState, setSwitchState] = useState(true); function handleOnChange(e: ChangeEvent<HTMLInputElement>) {
console.log("---", e.target.checked);
setSwitchState(!switchState);
} return (
<StyledLabel htmlFor="checkbox" checked={switchState}>
<input
id="checkbox"
type="checkbox"
checked={switchState}
onChange={handleOnChange} />
</StyledLabel>
);
}
So we’re using useState hook for storing the State
of the checkbox switchState
.
Since the checked
attribute is set on our form element, the checked value will always be switchState
, making the React state the source of truth.
When the handleOnChange
event is triggered, we then toggle the true/false booleen using setSwitchState
.
As HTML checkboxes have limited styling capabilities we will instead be styling the <label>
element and hide the checkbox. We are using styled components.
// Inside ToggleSwitch.tsx moduleconst StyledLabel = styled.label<{ checked: boolean }>`
cursor: pointer;
text-indent: -9999px;
width: 250px;
height: 125px;
background: ${({ checked }) => (checked ? COLORS.GREEN : COLORS.GRAY)};
display: block;
border-radius: 100px;
position: relative;&:after {
content: "";
position: absolute;
left: ${({ checked }) => (checked ? "14px" : "calc(55% - 5px)")}; top: 12px;
width: 100px;
height: 100px;
background: #fff;
border-radius: 90px;
transition: 0.3s;
}`;
You can now add your toggle switch component to App component.
Voila! we have our toggle switch ready! Also you can check my code here.