Files
30-seconds-of-code/snippets/Toggle.md
Isabelle Viktoria Maciohsek e7dd2358d0 Update Toggle
2020-09-06 14:48:13 +03:00

983 B

title, tags
title tags
Toggle components,state,beginner

Renders a toggle component.

  • Use the React.useState() to initialize the isToggleOn state variable to defaultToggled.
  • Use an object, style, to hold the styles for individual components and their states.
  • Return a <button> that alters the component's isToggledOn when its onClick event is fired and determine the appearance of the content based on isToggleOn, applying the appropriate CSS rules from the style object.
const Toggle = ({ defaultToggled = false }) => {
  const [isToggleOn, setIsToggleOn] = React.useState(defaultToggled);
  const style = {
    on: {
      backgroundColor: 'green'
    },
    off: {
      backgroundColor: 'grey'
    }
  };

  return (
    <button onClick={() => setIsToggleOn(!isToggleOn)} style={isToggleOn ? style.on : style.off}>
      {isToggleOn ? 'ON' : 'OFF'}
    </button>
  );
};
ReactDOM.render(<Toggle />, document.getElementById('root'));