React interview question

How to conditionally render components in react?


Conditional rendering is a term to describe the ability to render different user interface (UI) markup if a condition is true or false. In React, it allows us to render different elements or components based on a condition.

1. Element Variables:

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

function LogInComponent(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserComponent />;
  return <GuestComponent />;

  <LogInComponent isLoggedIn={false} />,


2. Inline If-Else with Conditional Operator:

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
        ? <LogoutButton onClick={this.handleLogoutClick} />
        : <LoginButton onClick={this.handleLoginClick} />

More Technical Interview Topics