Open In App

How to enable Button based on If statement in React.js ?

Last Updated : 09 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In order to display the button conditionally using the if and else statement, we can use state in react.js. Declare the state in the constructor method because it loads first when the component is loaded. In order to toggle between user and admin, we need to use an event handler. Using this event handler, we can toggle the state of the user. Below is the implementation of the code for displaying it.
 

Example: 

  • demo.js: 

    Javascript




    import React, {Component} from 'react'
      
    class DemoUser extends Component {
      
       constructor(){
         super()
         this.state = {
          isAdmin: true
         }
      
         this.toggleState = this.toggleState.bind(this);
       }
         
       toggleState() {
       this.setState ({
        isAdmin:!this.state.isAdmin }
       )
      
      
      
         
       render(){
        if(this.state.isAdmin){
          return(
          <div>
          <h3> Welcome Admin </h3><span > 
          Is the user admin : 
          {this.state.isAdmin.toString()}</span>
           <br/>
          <button  onClick={this.toggleState}>
            Toggle between user and admin
          </button>    
          </div>
          )
          }
        else{
          return(
          <div>
          <h3> Welcome User </h3><span >
           Is the user admin : 
           {this.state.isAdmin.toString()}</span>
           <br/>
          <button  onClick={this.toggleState}>
            Toggle between user and admin
          </button>    
          </div>
          )          
        }       
      }
     }
      
     export default DemoUser

    
    

  • index.js:

    Javascript




    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import * as serviceWorker from './serviceWorker';
    import DemoUser from './demo'
      
      
    ReactDOM.render(
      <React.StrictMode>
        <DemoUser />
      </React.StrictMode>,
      document.getElementById('root')
    );
      
      
    serviceWorker.unregister();

    
    

Output:
 



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

Similar Reads