Menu

gitpiper

Toggle react Code Snippet in 2024

componentsstatebeginner

Last Updated: 25 March 2024

Renders a toggle component.

  • Use the useState() hook to initialize the isToggleOn state variable to defaultToggled.
  • Render an <input> and bind its onClick event to update the isToggledOn state variable, applying the appropriate className to the wrapping <label>.
.toggle input[type="checkbox"] { display: none; } .toggle.on { background-color: green; } .toggle.off { background-color: red; }
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> ); };
ReactDOM.render(<Toggle />, document.getElementById('root'));

react snippet similar to Toggle For You in March 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️