Conditional Rendering in REACT JS

Posted By : Shilpa Adlakha | 29-Jun-2017

Conditional Rendering in REACT JS

In React JS, you can create different components that encapsulate behavior which we require. Then, we can render only few of them, depending on the state of the application.

Conditional rendering in React works in the same manner the conditions work in JavaScript. We use IF keyword or conditonal operator to create elements representing the current state, and then React update the UI to match them.

function WelcomeUser(props) {
  return <h1>Welcome back!</h1>;
}

function WelcomeGuest(props) {
  return <h1>Please sign up.</h1>;
}

We'll create a Welcome component that displays either of these components depending on whether a user is logged in:

function Welcome(props) {
  const isLoggedInStatus = props.isLoggedIn;
  if (isLoggedInStatus) {
    return <WelcomeUser />;
  }
  return <WelcomeGuest />;
}


ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Welcome isLoggedInStatus={false} />,
  document.getElementById('root')
);

 

Element Variables:

We can use the variables to store elements. This helps us to conditionally render a part of the component while the rest of the output remain same.

Let us consider these two new components representing Logout and Login buttons:

function LoginUser(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutUser(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

In the example below, we will create a stateful component called LoginControl.

It will render either <LoginUser /> or <LogoutUser /> depending on its current state. It will also render a <Welcome /> from the previous example:

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedInStatus = this.state.isLoggedIn;

    let button = null;
    if (isLoggedInStatus) {
      button = <LogoutUser onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginUser onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Welcoem isLoggedInStatus={isLoggedIn} />
        {button}
      </div>
    );
  }
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

While declaring a variable and using an if statement is a fine way to conditionally render a component.

 

Thanks!

 

About Author

Author Image
Shilpa Adlakha

Shilpa is a bright Wordpress Developer, she has good knowledge of HTML, CSS, PHP and Wordpress.

Request for Proposal

Name is required

Comment is required

Sending message..