Skip to content

Conditional rendering in React

How to dynamically output something vs something else in React

In a React component JSX you can dynamically decide to output some component or another, or just some portion of JSX, based on conditionals.

The most common way is probably the ternary operator:

const Pet = (props) => {
  return (
    {props.isDog ? <Dog /> : <Cat />}
  )
}

Another way, which works great when you conceptually have an if but not an else is to use the && operator, which works this way: if the expression before it evaluates to true, it prints the expression after it:

const Pet = (props) => {
  return (
    {props.isDog && <Dog />}
    {props.isCat && <Cat />}
  )
}
→ Download my free React Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about react: