/  Technology   /  How do you conditionally render components in React JS
How do you conditionally render components in React JS

How do you conditionally render components in React JS

 

The Conditional rendering in React works the same way conditions work in JS(JavaScript). Use JS(JavaScript) operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.

Consider these 2 components:

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

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

We will create a welcome component that displays either of these components depending on whether a user is logged in:

function Welcome(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
// Try changing to isLoggedIn={true}:
root.render(<Greeting isLoggedIn={false} />);

This example renders a different ways to welcome depending on the value of isLoggedIn prop.

You can use variables to store elements and this can help you conditionally render a part of the component while the rest of the output doesn’t change.

Consider these 2 new components representing Logout and Login buttons:

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

In the example below, we’ll create a stateful component called Logins.

It will render either Login or Logout depending on its current state. It will also render a Welcome from the previous example:

class Logins 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 isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) {
      button = <Logout onClick={this.handleLogoutClick} />;
    } else {
      button = <Login onClick={this.handleLoginClick} />;
    }
    return (
      <div>
        <Welcome isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }
}
const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<LoginControl />);

While declaring a variable and using an if statement is a fine way to conditionally render a react component, and sometimes you might want to use a shorter syntax. There are a few ways to inline conditions in JSX, and explained below.

Inline If with Logical && Operator

You may embed expressions in JSX(JavaScript XML) by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally render including an element:

function Mails(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Mailbox unreadMessages={messages} />);

It works because in JS(JavaScript), true && expression always evaluates to expression, and false && expression always evaluates to the false.

I.e, if the condition is true, the element right after && will appear in the  output, and if it is false, React will ignore and skip it.

Inline If-Else with Conditional Operator

Another method for conditionally rendering elements inline is to use the JS(JavaScript) conditional operator condition ? true : false.

In the below example, we use it to conditionally render a small block of text.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

 

Leave a comment