How do you conditionally render things in React?

Words
96
Reading
1 min
Listen
Play
6y

There are two ways of doing so. If we have have a class based component that contains an array of names in the state like :

react.jpeg

  state =
{  names:['liz', 'liza', 'blue']}

We could create a function below the state, and before the render method to display the names only if the length is greater than zero:

 renderNames(){        

   if

(this.state.names.length ===0) return <p>There are no names</p>;        

return 
<ul>{this.state.names.map(name=><li key={name}>{name}</li>)}</ul>}

In the render method, we could then return it like

   return

   (<div>{this.renderNames()}</div> )}

A second way would be to use the logical operator :

render(){ return(<div>{this.state.names.length ===0 && 'no names'}</div>)}

Meaning,if the first half is true, then it will render what’s at the right of it:

this.state.names.length ===0

//if true, render the text of 'no names'.

How do you conditionally render things in React? | Ecency