Monday, November 18, 2024
Google search engine
HomeLanguagesHow to implement toggle using ReactJS ?

How to implement toggle using ReactJS ?

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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments