Skip to content
Related Articles

Related Articles

Improve Article
How to enable Button based on If statement in React.js ?
  • Last Updated : 09 Oct, 2020

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:
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :