A toggle button is a component that can switch between two states, such as on and off, true and false, or selected and deselected. It's a user-friendly way to let users change a setting or attribute without needing to navigate away from the current page or open a new dialog box.
In React, a toggle button can be implemented as a functional component that uses state to keep track of whether it's currently toggled on or off. The state of the button can be changed with a simple click, making it an intuitive and efficient UI element.
In the following sections, we will guide you through the process of creating a toggle button in a new React project, from building the toggle button component to managing state changes and styling the button for a better user experience. Along the way, we'll also discuss some advanced topics and best practices to help you create more complex and interactive components.
Before we can start building our toggle button component, we need to import the necessary libraries and components into our React project. This includes the core React library, the useState hook for managing state, and any other components or CSS files we might need.
1import React, { useState } from 'react'; 2import './ToggleButton.css';
In the above code snippet, we are importing the React library and the useState hook from the react package. We are also importing a CSS file named ToggleButton.css which will contain the styles for our toggle button component.
With the necessary libraries and components imported, we can now proceed to create our toggle button component. This component will be a functional component that uses the useState hook to manage its state.
The initial state of the toggle button will be false, indicating that the button is off by default. We will also define a handleChange function that will be triggered when the user clicks on the button. This function will toggle the state of the button, switching it from off to on, or vice versa.
1export default function ToggleButton() { 2 const [isToggled, setIsToggled] = useState(false); 3 4 const handleChange = () => { 5 setIsToggled(!isToggled); 6 }; 7 8 return ( 9 <button onClick={handleChange} className={`toggle-button ${isToggled ? 'on' : 'off'}`}> 10 {isToggled ? 'ON' : 'OFF'} 11 </button> 12 ); 13}
In the above code snippet, we are creating a functional component named ToggleButton. We are using the useState hook to create a state variable isToggled and a function to update it setIsToggled. The handleChange function toggles the state of the button when it is clicked.
The return statement of the component renders a button element. The onClick handler of the button is set to the handleChange function, so it gets triggered when the button is clicked. The class of the button is dynamically set based on the state of the button, and the text displayed on the button is also based on its state.
In React, the useState hook is a built-in function that allows us to add a React state to our functional components. It is part of a group of features in React called Hooks that were introduced in React 16.8.
The useState hook accepts one argument, the starting state, and returns an array with the current state (akin to this.state in a class component) and a function to update it (similar to this.setState).
1const [state, setState] = useState(initialState);
In the context of our toggle button component, we use the useState hook to create a state variable isToggled and a function to update it setIsToggled. The isToggled state variable is used to keep track of whether the button is on or off.
The initial state of our toggle button is set to false, indicating that the button is off by default. This is passed as an argument to the useState hook when we create our state variable.
1const [isToggled, setIsToggled] = useState(false);
The useState hook ensures that the initial state is only assigned during the first render. In subsequent renders, it will return the current state.
When the setIsToggled function is called with a new state, React schedules a re-render with the updated state. This is how the toggle button knows to update its display and behavior when it is clicked.
The callback function is a crucial part of our toggle button component. It's responsible for changing the state of the button when it's clicked. In our case, the callback function is handleChange.
1const handleChange = () => { 2 setIsToggled(!isToggled); 3};
In the handleChange function, we call setIsToggled with the negated value of isToggled. This effectively toggles the state of the button between true and false.
The onClick handler is a prop in React that is triggered when the user clicks on an element. In our toggle button component, we set the onClick handler of the button to the handleChange function.
1<button onClick={handleChange} className={`toggle-button ${isToggled ? 'on' : 'off'}`}> 2 {isToggled ? 'ON' : 'OFF'} 3</button>
When the button is clicked, the onClick handler triggers the handleChange function, which toggles the state of the button.
The handleChange function and the onClick handler work together to create the toggle functionality of the button. When the button is clicked, the onClick handler triggers the handleChange function. The handleChange function then calls setIsToggled with the negated value of isToggled, toggling the state of the button.
To customize the appearance of our toggle button, we can define specific styles in a CSS file and import it into our component.
First, let's create a ToggleButton.css file and add the following styles:
1.toggle-button { 2 padding: 10px 20px; 3 background-color: #ddd; 4 border: none; 5 cursor: pointer; 6 font-size: 16px; 7 transition: background-color 0.3s ease; 8} 9 10.toggle-button.on { 11 background-color: #4CAF50; 12 color: white; 13} 14 15.toggle-button.off { 16 background-color: #f44336; 17 color: white; 18}
In the above CSS, we have defined common styles for the toggle button, as well as specific styles for when the button is in the 'on' and 'off' states.
The border-radius and width of the button can be adjusted to make it more visually appealing. For example, we can give the button a border radius to make it round and adjust its width to make it wide enough to fit its content.
1.toggle-button { 2 border-radius: 50%; 3 width: 100px; 4}
Accessibility is an important aspect of web development. The aria-label attribute is used to define a string that labels the current element. It is used to provide an accessible name for objects that can be read by assistive technology.
In our toggle button component, we can use the aria-label attribute to provide a descriptive label for the button, such as "Toggle button".
1<button 2 onClick={handleChange} 3 className={`toggle-button ${isToggled ? 'on' : 'off'}`} 4 aria-label="Toggle button" 5> 6 {isToggled ? 'ON' : 'OFF'} 7</button>
The handleChange function is a callback function that we have defined in our ToggleButton component. This function is responsible for toggling the state of the button when it is clicked.
1const handleChange = () => { 2 setIsToggled(!isToggled); 3};
In the handleChange function, we call setIsToggled with the negated value of isToggled. This effectively toggles the state of the button between true and false.
The handleChange function is used as the onClick handler for the button. When the button is clicked, this function is triggered, which toggles the state of the button.
1<button 2 onClick={handleChange} 3 className={`toggle-button ${isToggled ? 'on' : 'off'}`} 4> 5 {isToggled ? 'ON' : 'OFF'} 6</button>
In the above code, the onClick prop of the button is set to the handleChange function. So, when the button is clicked, the handleChange function is executed, toggling the state of the button.
When the state of the button changes, React automatically re-renders the component to reflect the new state. The current state of the button is accessed through the isToggled state variable, and the button's class and displayed text are updated based on this state.
As you become more comfortable with creating a basic toggle button, you might want to explore more complex setups. For instance, you could create a group of child buttons that each maintain their own state but also influence the state of a parent component. This can be achieved by lifting the state up to the parent component and passing down the state and the state-modifying functions as props to the child buttons.
Props in React allow components to interact with each other by passing values from a parent component to a child component. For example, a parent component could pass a callback function as a prop to a child component, and this function could be called within the child component to trigger changes in the parent component's state.
Debugging is an essential skill for any developer. In React, you can use the console.log() function to log values to the console for debugging purposes. This can be particularly useful when trying to understand how state changes over time or how different components interact with each other.
Building a toggle button in React involves understanding several key concepts, including components, state, props, and event handlers. As you continue to learn and build more complex applications, you'll find that these concepts are fundamental to React and many other JavaScript frameworks.
Creating a toggle button in React involves understanding several key concepts, including components, state, props, and event handlers. This guide has walked you through each step of the process, from building the toggle button component to managing state changes and styling the button.
By following this guide, you should now have a solid understanding of how to create a toggle button in React, and how to use the useState hook and callback functions to manage state changes. You should also have learned how to style your button using CSS and how to make your button accessible with the aria-label attribute.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.