Toggles are a common UI element used to switch between two states or options in a user interface. In ReactJS, implementing toggle functionality is straightforward and can be achieved using state management and event handling. In this article, we will explore how to implement a toggle feature using ReactJS.
If we want to implement toggle functionality to a button, then we can have states in our component that will either be true or false and based on the value of state we can implement toggle functionality. When we click on the button and the current value of the state is true then we changed it to false and vice versa. When we change the state the component will re-render and based on the value of state content will display.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure:
Example: Here we will create a button component to toggle, we will use the JavaScript this keyword as well.
App.js
Javascript
import React from 'react' class Counter extends React.Component { render() { return ( <div> <Button text= "Hello from GFG" > </Button> </div> ) } } class Button extends React.Component { state = { textflag: false , } ToggleButton() { this .setState( { textflag: ! this .state.textflag } ); } render() { return ( <div> <button onClick={() => this .ToggleButton()}> { this .state.textflag === false ? "Hide" : "Show" } </button> {! this .state.textflag && this .props.text} </div> ) } } export default Counter; |
Output: