Conditional rendering in React

Author Purushothaman Raju ,Posted on May 26 2020

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;
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;

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;

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;