Advertisement
Beginner React, Conditional Rendering & Lists (Keys)

How do you show different content in React depending on a condition?

Short answer

You can use a regular JavaScript if statement before the return, a ternary expression directly inside JSX, or the double ampersand operator when you only want to show something in one specific case and nothing otherwise.

Save React mock interview
Advertisement
AModel answer
You can use a regular JavaScript if statement before the return, a ternary expression directly inside JSX, or the double ampersand operator when you only want to show something in one specific case and nothing otherwise.
function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back</p> : <p>Please log in</p>}
      {isLoggedIn && <button>Log Out</button>}
    </div>
  );
}
Real-world example
A website shows a personalized welcome message and a logout button only for signed in users, while showing a simple login prompt to everyone else, all controlled with basic conditional checks.
Likely follow-ups
  • What is the difference between using a ternary and using the double ampersand operator?
  • What happens if a condition's value is the number zero when used with the double ampersand operator?
Related topics