Build an on/off toggle switch with controlled state.
Skip to solutionKEEP THE
easyMachine Coding
Build a Toggle Switch
985 views
01
Understand the problem
ReactStateUI
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Solve in
Building a controlled toggle switch in React involves managing its on state and providing a way to update it. The core idea is to let a parent component dictate the toggle's state and handle state changes, making the toggle reusable and predictable.
Step 1 — Define the Toggle Component Structure
Start by creatin
Solution ready — 2 min read
Classified // press E to declassify
04
React solution
Complete solutionRun Playground
import React, { useState } from 'react';
import ToggleSwitch from './src/ToggleSwitch';
const App = () => {
const [isToggled, setIsToggled] = useState(false);
const handleToggle = () => {
setIsToggled((prev) => !prev);
};
return (
<div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
<h1>Toggle Switch Demo</h1>
<ToggleSwitch isOn={isToggled} onToggle={handleToggle} />
<p style={{ marginTop: '20px', fontSize: '18px' }}>Current State: <strong style={{ color: isToggled ? 'green' : 'red' }}>{isToggled ? 'ON' : 'OFF'}</strong></p>
</div>
);
};
export default App;05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 8 of 87 decoded in the Frontend Machine Coding track. One more won't hurt.