Open In App

How to implement toggle using ReactJS ?

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Toggles are a common UI element used to switch between two states or options in a user interface. In ReactJS, it can be achieved using state management and event handling. In this article, we will explore how to implement a toggle feature using ReactJS.

Prerequisites

Steps to create 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

Javascript




// App.js
 
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:

Animation12



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads