Conditional rendering in React

problemsolver03

Purushothaman Raju

Posted on December 23, 2021

Conditional rendering in React

To decide which UI elements to show or render in react is what we refer to as conditional rendering. This can be achieved by 3 ways which are helper functions, using ternary operators, and lastly by using simple if-else conditions in the render method. let us see some code examples to better understand these techniques.

Conditional rendering using helper functions
The idea is we abstract the logic from the render method and add it inside a function that will return some JSX or UI based on some conditions.
Here is an example

class App extends React.Component{
  helperFunction = () => {
      return (
          <h2>
              I was returned from a helper function
          </h2>
      )
  }
  render() {
      return (
          <div>
              {this.helperFunction()}
          </div>
      )
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode
class App extends React.Component {
  render() {

    const helper = () => {
      return <h2>I was returned from a helper function</h2>;
    };

    return <div>{helper()}</div>;
  }  
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Using Ternary operators
This is the most common way of handling conditional rendering in the react world to show a price of UI or to manipulate the values like adding classNames or showing values inside elements, this usually written inside the return method of components.
Let us see an example to understand this approach better

class App extends React.Component {

  state = {
    data:true
  }

  render() {

    return (
      <div>
        {
          this.state.data ? <p>Data is available</p> : <p>Sorry no data can be shown</p>
        }
      </div>
    )
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Use of If/Else conditions
This is a very straight forward approach to decide which piece of UI or JSX we want to return to the user. see the below example to
understand this approach better.

class App extends React.Component {  
  state = {
    data:true
  }
  render() {
    if (this.state.data) { 
      return (<p>Data is available</p>)
    }
    else {
      return (<p>Sorry not data is available</p>)
    }    
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

if you like this article please do visit my blog here www.uiuxtek.in

💖 💪 🙅 🚩
problemsolver03
Purushothaman Raju

Posted on December 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related