Conditional rendering in React

How to dynamically output certain content vs. other content in React

In React component JSX, you can dynamically decide to output a certain component or other components according to conditions, or just a part of JSX.

The most common way is probably the ternary operator:

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

Another way, when you conceptually have aifbut notelseIs to use&&Operator, it works as follows: if the previous expression evaluates to true, the expression will be printed after it:

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

Download mine for freeResponse Handbook


More response tutorials: