Conditional Rendering 🤔
Conditional rendering in React isn't difficult. In JSX - the syntax extension used for React - you can use plain JavaScript which includes if else statements, ternary operators, switch case statements, and much more. In a conditional render, a React component decides based on one or several conditions which DOM elements it will return
When a component has a conditional rendering, the appearance of the rendered component differs based on the condition.
👉 Conditional Rendering in React: if
Conditional Rendering in React: if else
Conditional Rendering in React: ternary
Conditional Rendering in React: &&
Conditional Rendering in React: switch case
Multiple Conditional Renderings in React
Nested Conditional Rendering in React
Conditional Rendering with HOC If Else Components in React
CONDITIONAL RENDERING IN REACT: IF
The most basic conditional rendering logic in React is done with a single if statement. Imagine you don't want to render something in your React component, because it doesn't have the necessary React props available. For instance, a List component in React shouldn't render the list HTML elements in a view if there is no list of items in the first place. You can use a plain JavaScript if statement to return earlier (guard pattern):
const users = [
{ id: '1', firstName: 'Daniel', lastName: 'Smith' },
{ id: '2', firstName: 'Tom', lastName: 'Garlov' },
]
function App() {
return (
<div>
<h1>Conditional Rendering</h1>
<List list={users} />
</div>
)
}
function List({ list }) {
if (!list) {
return null
}
return (
<ul>
{list.map((item) => (
<Item key={item.id} item={item} />
))}
</ul>
)
}
function Item({ item }) {
return (
<li>
{item.firstName} {item.lastName}
</li>
)
}
👉 In this code, the conditional rendering is based on props, but the conditional rendering could be based on state and hooks too.
CONDITIONAL RENDERING IN REACT: IF ELSE
Let's move on with the previous example to learn about if else statements in React. If there is no list, we render nothing and hide the HTML as we have seen before with the single if statement. However, you may want to show a text as feedback for your user when the list is empty for a better user experience. This would work with another single if statement, but we will expand the example with an if else statement instead:
function List({ list }) {
if (!list) {
return null
}
if (!list.length) {
return <p>Sorry, the list is empty.</p>
} else {
return (
<div>
{list.map((item) => (
<Item item={item} />
))}
</div>
)
}
}