Reusable React Toggle Component

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to implement a toggle component using React. The toggle component is a common UI element used to switch between two states. We will use the useState() hook to manage the component's state and apply different CSS classes based on its state. By the end of this lab, you will have a better understanding of how to create reusable UI components in React.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38366{{"`Reusable React Toggle Component`"}} react/event_handling -.-> lab-38366{{"`Reusable React Toggle Component`"}} react/conditional_render -.-> lab-38366{{"`Reusable React Toggle Component`"}} react/hooks -.-> lab-38366{{"`Reusable React Toggle Component`"}} react/use_state_reducer -.-> lab-38366{{"`Reusable React Toggle Component`"}} end

Toggle

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To render a toggle component, follow these steps:

  1. Use the useState() hook to initialize the isToggledOn state variable to defaultToggled.
  2. Render an <input> element and bind its onClick event to update the isToggledOn state variable. Apply the appropriate className to the wrapping <label> element.
  3. Use the following CSS to style the toggle component:
.toggle input[type="checkbox"] {
  display: none;
}

.toggle.on {
  background-color: green;
}

.toggle.off {
  background-color: red;
}

Here's the code:

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 />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Toggle lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like