Skip to content
Related Articles

Related Articles

Improve Article

How to implement toggle using ReactJS ?

  • Last Updated : 08 Apr, 2021

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




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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :