To make a toggle button accessible, we should add aria-label
to describe the button’s function and aria-checked
to indicate its state. These attributes help screen readers provide meaningful feedback to users.
Key takeaways:
A toggle component in React allows users to switch between two states, such as light and dark mode. A toggle button also allows users to control an element's visibility or functionality.
useState
Hook is essential for managing the state of a React component. It allows components to track and update their state, trigger rerenders, and enable conditional rendering.
Conditional rendering is a core feature in React. It allows components to dynamically change their display based on state or props.
Functional components are commonly used in modern React development, especially with the introduction of hooks like useState
, which simplifies state management compared to class components.
A React component is a piece of code that represents and handles a specific UI functionality in a React application. It can be either a class-based or a functional component, and it returns JSX (HTML-like syntax) that React renders. Components can manage state and side effects, making them reusable and independent. Each React component is independent and reusable; we can have as many components as our application requires. These components can be used on multiple pages of the application.
In simple words, React components are the building blocks that combine to form a complete and functional React application. For example, there can be components for the navigation bar, footer, toggle button (such as a dark mode toggle), and so on. While we can work on them individually, they can all be used together to build the final application.
Toggling refers to handling the visibility or state of an element in the application. A toggle component in React, such as a toggle button, acts like a switch that, once clicked, will show or hide an element or a group of elements. In this Answer, we’ll create a React toggle button from scratch. However, third-party libraries like react-toggle
and react-switch
also provide us with built-in toggle components. Using these libraries is convenient, but creating the component from scratch allows us to customize it to suit the specific needs of our application.
Since we want to show or hide elements by clicking a toggle button in React, we’ll maintain the state of the toggle button in our React component. Depending on this state, we’ll conditionally render the element(s) on the page. Once clicked, the state of the toggle button will change, which triggers updates in the UI, such as switching between light and dark mode.
Let’s look at an example of a React toggle button component implemented as a function that returns HTML.
import "./toggle.css";const Toggle = ({ toggle, handleToggleChange }) => {return (<div className='toggle-container' onClick={handleToggleChange}><div className={`toggle-btn ${!toggle ? "disable" : ""}`}>{toggle ? "ON" : "OFF"}</div></div>);};export default Toggle;
In the above code:
Line 1: Import the toggle.css
file that defines the style and format of the toggle button.
Line 3: Create the Toggle
function component that receives the following props:
toggle
: The state of the toggle button.
handleToggleChange
: A function handle that will change the state of the toggle button upon any change.
Lines 4–10: The Toggle
function returns the HTML code for the toggle button. The onClick
event handler triggers the state change of the toggle button.
Line 13: The export default Toggle
statement makes the Toggle
component available for use anywhere in the application.
Now that we have the toggle component in React, we can use it on any page in the application. Let’s see how to integrate it into the main App
component.
import { useState } from "react";import Toggle from "./components/Toggle";function App() {const [toggle, setToggle] = useState(false);const handleToggleChange = () => {setToggle(!toggle);};return (<divclassName='App'style={toggle ? { backgroundColor: "black"} : { backgroundColor: "white"}}><Toggle toggle={toggle} handleToggleChange={handleToggleChange} /></div>);}export default App;
In the above code:
Line 2: Import the Toggle
component we created.
Line 5: Use the useState
Hook to track the state of the toggle button. It initializes the state with false
, and setToggle
updates the state when triggered.
Lines 6–8: Once handleToggleChange
function uses setToggle
to toggle the state between true
and false
.
Lines 9–16: Render the application page, which includes the Toggle
component. Depending on the value of toggle
, the background and text color of the page are conditionally styled to either light or dark mode (line 12).
Toggle
component applicationFinally, here’s how the application works. Click the “Run” button to execute the code. Once the server starts, we can interact with the application in the output tab or visit the URL shown next to “Your app can be found at:” to view the application in a new browser tab.
import { useState } from "react"; import Toggle from "./components/Toggle"; import './App.css'; function App() { const [toggle, setToggle] = useState(false); const handleToggleChange = () => { setToggle(!toggle); }; return ( <> <div className='App' style={toggle ? { backgroundColor: "black" , color: "white"} : { backgroundColor: "white" , color: "black"}} > <Toggle toggle={toggle} handleToggleChange={handleToggleChange} /> </div> </> ); } export default App;
The code above executes and displays the application page with a toggle button to enable or disable the dark mode.
Let’s attempt a short quiz to assess your understanding.
What is the primary purpose of the useState
Hook in the toggle component example?
To style the component based on its current state
To import CSS styles for the toggle component
To manage and update the state of the toggle, allowing conditional rendering
To add accessibility features like aria-label
and aria-checked
In this Answer, we created a simple toggle component in React to switch between light and dark modes. We managed the state with the useState
Hook and used conditional rendering for flexibility. Accessibility features like aria-label
and aria-checked
were added for screen reader support, making the toggle user-friendly. Building this component from scratch provides more control over its appearance and behavior, serving as a foundation for toggle functionality in React apps.
React offers both functional components and class components. With the introduction of Hooks, functional components have become popular for their simplicity. Hooks like useState
allow functional components to handle the state without the setState
method used in class components. This approach is especially beginner-friendly and aligns with modern React practices.
Haven’t found what you were looking for? Contact Us
Free Resources