Files
30-seconds-of-code/react/snippets/toggle.md
Angelos Chalaris 462322f885 Prepare for merge
2023-05-01 22:56:37 +03:00

1.0 KiB

title, type, tags, cover, dateModified
title type tags cover dateModified
Toggle snippet
components
state
cows 2020-11-16T16:50:57+02:00

Renders a toggle component.

  • Use the useState() hook to initialize the isToggledOn 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.createRoot(document.getElementById('root')).render(
  <Toggle />
);