Skip to content

Latest commit

 

History

History
57 lines (44 loc) · 1.02 KB

conditional-rendering-in-components.md

File metadata and controls

57 lines (44 loc) · 1.02 KB

Conditional Rendering In Components

Category: React

Conditional rendering in React components can be done using element variables or inline if statements.

Element variables

You can use variables to store elements and render the output:

type HeaderProps = {
  text: string;
  loggedIn: boolean;
}

const Header = ({ text, loggedIn } : HeaderProps) => {

  let heading;
  if (loggedIn) {
    heading = <Logout>Logout {text}</Logout>
  } else {
    heading = <Login>Login {text}</Login>
  }

  return (
    <div>
      {heading}
    </div>
  );
}

Inline if with logical && operator

Expressions can be wrapped using curly braces. The JavaScript logical && operator can conditionally render an element:

type HeaderProps = {
  text: string;
  loggedIn: boolean;
}

const Header = ({ text, loggedIn } : HeaderProps) => {

  return (
    <div>
      {loggedIn &&
        <Logout>Logout {text}</Logout>
      }
      {!loggedIn &&
        <Login>Login {text}</Login>
      }
    </div >
  );
}