Toggle
React, Components, State · Nov 16, 2020

Renders a toggle component.
- Use the
useState()
hook to initialize theisToggledOn
state variable todefaultToggled
. - Render an
<input>
and bind itsonClick
event to update theisToggledOn
state variable, applying the appropriateclassName
to the wrapping<label>
.
const Toggle = ({ defaultToggled = false }) => {
const [isToggleOn, setIsToggleOn] = React.useState(defaultToggled);
return (
<label className={isToggleOn ? 'toggle on' : 'toggle off'}>
<input
type="checkbox"
checked={isToggleOn}
onChange={() => setIsToggleOn(!isToggleOn)}
/>
{isToggleOn ? 'ON' : 'OFF'}
</label>
);
};
.toggle input[type="checkbox"] {
display: none;
}
.toggle.on {
background-color: green;
}
.toggle.off {
background-color: red;
}
ReactDOM.render(<Toggle />, document.getElementById('root'));