👋 Today, we’re doing a bit of css with a cool little project: building a toggle switch with a smooth transition using React and TypeScript. The full code is available on CodeSandbox. Let’s get started!
The Goal
We’re going to create a toggle switch that allows users to switch between gallery and list views. The switch will have a smooth sliding animation and change colors to indicate the active state. Here’s what we’re aiming for:
Setting Up
First, let’s break down the components we’ll be using:
- A container for our toggle
- A sliding background element
- Two clickable areas for each view option containing the SVG Icon
The Container
Our main container sets up the overall shape and style of the toggle:
<div
style={{
display: "flex",
borderRadius: "100px",
backgroundColor: "#0036FF80",
position: "relative",
width: "140px",
height: "32px",
}}
>
{/* Icons and clickable areas will go here */}
{/_ ... _/}
</div>
We’re using inline styles here, but feel free to use tailwinds or styled-components.
The Sliding Background
Here’s where the magic happens:
<div
style={{
position: "absolute",
top: 0,
left: 0,
width: "50%",
height: "100%",
backgroundColor: "#0036FF",
borderRadius: "40px",
transition: "transform 0.3s ease",
transform: view === "gallery" ? "translateX(0)" : "translateX(100%)",
}}
/>
This div acts as our sliding background. The key properties are:
position
: absolute to take it out of the normal flowwidth
: 50% to cover half of the toggletransition
: transform 0.3s ease for smooth animationtransform
to move the background based on the current view
The Clickable Areas
For each view option, we have a clickable area:
<div
style={{
flex: 1,
display: "flex",
justifyContent: "center",
alignItems: "center",
zIndex: 1,
cursor: "pointer",
}}
onClick={() => setView("gallery")}
>
<GalleryViewIcon
style={{ color: view === "gallery" ? "white" : `#FFFFFF80` }}
/>
</div>
The onClick handler
updates the view state, and we change the icon color based on whether it’s active or not.
Wrapping Up
And there you have it! A smooth, animated toggle switch built with React and TypeScript.
Remember, the key to the smooth transition is in the CSS transition property and the dynamic transform based on the current state. Play around with these values to customize the feel of your toggle! The full code is available on CodeSandbox.
Happy coding 👨💻👩💻