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
// App component (parent)
const App = ({}) => {
  const [counter, setCounter] = React.useState(0)
  React.useEffect(() => {
    const timer = setTimeout(() => {
      setCounter(counter + 1)
    }, 1000)
    return () => {
      clearTimeout(timer)
    }
  }, [counter])

  // if `counter > 5`, display current value of `counter` enclosed between `<h1>` element
  if (counter > 5) {
    return <h1>{counter}</h1>
  }

  return (
    <>
      {/*ternary operator*/}
      {counter === 0 ? <h2>Starting...</h2> : ''}

      {/* Logical AND (&&) operator*/}
      {counter >= 1 && counter <= 5 && <h3>{counter}</h3>}
    </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

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?

Related Posts

ReactJS
How to set dynamic inner text with React.createElement()?
July 19, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media