Conditional rendering in React
Rendering a component based on a state is called Conditional Rendering.
Conditional rendering in React works similar to vanilla javascript, you can use operators like if
or you can use ternary
operator.
inline if condition
consider you have a list of items and you need to display items of lists only when there is minimum of 1 element in the list.
you can do this like below
const [data, setData] = useState([])
..
..
return (
<div>
{ data.length > 0 && <h1> Not empty </h1> }
</div>
)
The above returns only when the list has atleast 1 element.
if-else conditions
Well, if you want to display that list is empty when the list is empty, you need a else
case as well. we can do it easily with ternary
operator as below
const [data, setData] = useState([])
..
..
return (
<div>
{ data.length > 0 ? <h1> Not empty </h1> : <h1> empty </h1> }
</div>
)
The above code returns empty
when the list has no elements else not empty