Attention to Minor Details in React’s Conditional Rendering : Basics 01

Mahesh Guntumadugu
3 min readSep 15, 2023
Photo by Lautaro Andreani on Unsplash

Let’s say we have a component that renders a list of items. I have just used “item” as the key for simplicity’s sake. In the real world, data will be fetched from the server, and it should ideally have a unique ID.

Note: I am using the bootstrap library class in code snippet. You can use your own and change the classes accordingly.

function ListGroup() {
let items = ["Banglore", "Hyderabad", "Delhi", "Mumbai"];
return (
<>
<h1>List</h1>
<ul className="list-group">
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</>
);
}

export default ListGroup;

let’s code how to achieve conditional rendering.When the list is empty, we want to render a custom message. One way to go about this is to write an if condition and render different markup. Notice I have just set the list to empty and added an if condition to achieve this.

function ListGroup() {
let items = ["Banglore", "Hyderabad", "Delhi", "Mumbai"];
items = [];

if (items.length === 0)
return (
<>
<h1>List</h1>
<p>No item found</p>;
</>
);
return (
<>
<h1>List</h1>
<ul className="list-group">
{items.map((item) => (
<li key={item}>{item}</li>
))}…

--

--

Mahesh Guntumadugu

I'm not just a Senior Engineer— My belief? The world is a better place when we lift each other up. 😃. https://www.curiousengineers.in