Reactjs Toggle

Author - Toggle - ReactJS Component
Cristian
August 26th, 2020
Toggle - ReactJS Component

Toggle - ReactJS Component

We use the React.useState() to initialize the isToggleOn state variable to false.

After that, we create an object, status, to hold the styles for individual components and their states.

We return a <button> that alters the component's isToggleOn when its onClick event is fired and determine the appearance of the content based on isToggleOn, applying the appropriate CSS rules from the status object.

const Toggle = (props) => {
  const [isToggleOn, setIsToggleOn] = React.useState(false);
  const status = {
    on: {
      backgroundColor: "green"
    },
    off: {
      backgroundColor: "grey"
    }
  };
  return (
    <button
      onClick={() => setIsToggleOn(!isToggleOn)}
      style={isToggleOn ? status.on : status.off}
    >
      {isToggleOn ? "ON" : "OFF"}
    </button>
  );
}
ReactDOM.render(
    <Toggle />, 
    document.getElementById('root')
);