Introduction
Sometimes we want to show a React component when a condition yields true. It is called Conditional Rendering. Also, rendering through a list of values to display a Component multiple times is very common in React. In this blog, we are discussing these two topics.
Conditional Rendering in Action
In React, we can use any valid JavaScript code inside JSX. So, we can conditionally render a Component with these two operators in React:
- Using Logical And Operator (&&).
- Using Ternary Operator (?:).
1. Using Logical And Operator (&&):
Logical And Operator is used if you want to render a component only when a condition yields true. We can compare it with the if condition. But it can’t handle the else case. Below is a simple example of Logical And Operator:
import { useState } from 'react';
const App = () => {
const [isActive, setIsActive] = useState(true);
return (
<div>
<h1>Active User</h1>
{
isActive && <p>User is Active Now.....</p>
}
</div>
)
}
export default App;
2. Using Ternary Operator (?:):
Ternary Operator is used if you want to render one component only when a condition yields true and another Component if yields false. Below is a simple example of a Ternary Operator:
import { useState } from 'react';
const App = () => {
const [isActive, setIsActive] = useState(true);
return (
<div>
<h1>Active User</h1>
{
isActive?
<p>User is Active Now.....</p>
:
<p>User is Offline Now...</p>
}
</div>
)
}
export default App;
Rendering List
In React, we use the map
function to render a list of components. We can loop through arrays or an array of objects with this method. Here we need to pass a key
attribute for all the returned elements from the map
function. This key
should be a unique identifier. Below is an example of a Rendering List in React:
const App = () => {
const todos = [
{
id: 0,
title: "Go to Gym",
},
{
id: 1,
title: "Make Tea",
},
];
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
export default App;
Why should indexes not be used as keys?
In React, we use the index of an element as a key
attribute. But this is an anti-pattern. We shouldn’t do this. For elements, having key
as an index, every time we add a new element or delete an existing element from the list, other element keys may change. This results re-rendering of the whole list. And we always need to avoid unnecessary re-renders in our front end. So, always use a unique id field as the key
, not the index.
Summary
In this blog, We have discussed Conditional Rendering, Logical And Operator, Ternary Operator, Rendering Lists and why should indexes not be used as keys. Follow me to learn more about React and other Frontend Development skills.
Top comments (0)