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.
Toggle
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
To render a toggle component, follow these steps:
- Use the
useState()hook to initialize theisToggledOnstate variable todefaultToggled. - Render an
<input>element and bind itsonClickevent to update theisToggledOnstate variable. Apply the appropriateclassNameto the wrapping<label>element. - 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.