in React JS by
Q:

How do you conditionally render components?

1 Answer

0 votes
by

In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address &&
      <p>{address}</p>
    }
  </div>
)

If you need an if-else condition then use ternary operator.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address
      ? <p>{address}</p>
      : <p>{'Address is not available'}</p>
    }
  </div>
)

Related questions

0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Jun 19, 2020 in React JS by JackTerrance
...