HomeTutorsContact

How to conditionally render a component in React?

By Gulshan Saini
Published in ReactJS
July 01, 2020
1 min read

Rendering a component in React can be done conditionally using plain JavaScript if/else, ternary or Logical AND(&&) operator.

In the following example, we have a variable counter whose initial value is 0 and we have three conditions based on which we are going to render different elements. The conditions are

  • if counter === 0, display text “Starting…” enclosed between <h3> element
  • if counter >= 1 && counter <= 5, display current value of counter enclosed between <h3> element
  • if counter > 5, display current value of counter enclosed between <h1> element

In the above example I have demonstrated different ways to render elements conditionally using plain JavaScript if/else, ternary or Logical AND(&&) operator.

You might also have noticed when I used if/else conditional statement, we returned from the component immediately.

if/else and ternary operator sometimes makes the code hard to read when you have a deep level of nested conditions.

Output


Tags

#react
Previous Article
How to pass all props from parent to child component in React?

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to set dynamic inner text with React.createElement()?

July 19, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media