Posted on 4/18/2025 2:55:24 AM by Admin

Conditional Rendering and Lists in React – Showing Data Dynamically

In the modern web, dynamically changing the data, updating the UI based on certain events, or reacting to user interactions has become crucial for a website to succeed. React excels in doing so and provides several ways to make your website more dynamic, interactive, and engaging. You can create highly dynamic UIs with React without putting too much effort into it. The 2 major concepts that provided this dynamism to React are conditional rendering and rendering lists.

In this article, we will explore these core concepts and learn how to implement them in order to enhance the dynamicity of our web pages.

Conditional Rendering

Conditional Rendering refers to rendering objects and components based on certain conditions. The objects render if these conditions are true and are not rendered if false. In React, there are several ways to implement conditional rendering, some of which are given below:

1. Using if/else Statements:

The standard if/else statement helps you render the JSX elements based on the specified condition. You can use it directly into the component's JavaScritp logic. To understand this, create a new component named Message.js and add the following code:


function Message(props) {
  let text;
  if (props.loggedIn) {
    text = <h1>Welcome back, {props.name}!</h1>;
  } 
  else {
    text = <h1>You are logged out.</h1>;
  }
  return <div>{text}</div>;
}

In the above code, different messages will be displayed on the screen based on whether the user is logged in or not.

2. Ternary Operator, aka Condition Operator

The ternary or conditional operator can be considered the short form of an if/else statement. It uses a condition to determine which block to render.


function Loading(props) {
  return props.isLoading ? <h1>Loading... <br> Please wait!</h1> : null;
}

In this example, the operator checks for the condition. If isLoading is set to false, it returns null, and if isLoading is true, it returns the specified message.

3. Short-Circuit Evaluation

You can use the logical AND (&&) operator to render an element only if a condition is true. React ignores the element after the && operator when the condition is false.


function AdminBtn(props) {
  return props.isAdmin && <button>Admin Panel</button>;
}

Preventing Rendering with null

When you want to hide an element completely, you can return null from the condition, as we have done in the Loading component example. It is a common technique to prevent a component or part of JSX from rendering.

Rendering Lists in React: Displaying Collections of Data

We often need to display data collections in React, such as a collection of users, employees, products, etc.; there's no better way to do that than by using lists. With the help of the JavaScript map() array function, you can easily render data lists in React.

map() Function

The map() method is used to iterate through each item in an array and apply a defined function to it. As a result, it returns a new array, transforming an array of data to an array of JSX elements so it can be rendered.

For instance, consider that we have an array of products:


const products = ['Mobile', 'Headset', 'Charger'];
const productList = products.map((product) => <li>{product}</li>);

return (
  <ol>{productList}</ol>
);

In the above code, we have an array of products that are converted to the list items with the map() method. The map() method iterates through each element and converts it to the list item. All the items are stored in the productList, which can be rendered as an ordered list.

The Crucial key Prop

The React's reconciliation process (an algorithm that updates the actual DOM) requires a special key prop when rendering lists dynamically. You must provide this prop as it helps React identify the items being added, removed, or changed. The React may struggle to update the UI correctly if the keys are not unique and stable, ultimately leading to performance issues.

Please note that this prop must be unique and stable for each item in the list.


const Students = [
  { id: 33, name: 'Khizer' },
  { id: 34, name: 'Sachin' },
  { id: 35, name: 'Hafsa' },
];

const studentsList = Students.map((student) => (
  <li key={student.id}>{student.name}</li>
));

return <ul>{studentsList}</ul>;

In the above code, we have used the student ID as the key, which ensures that React can easily track all the items, even if the list has been changed or reordered.

You can also use the array index as a key, but it is not recommended as the index of an item may change even if the item itself has not. This can lead to the DOM elements being reused incorrectly, inconsistent visuals, and performance issues.

Rendering Lists of Objects: Retrieving and Displaying Data

Usually, the data that you render using the lists will consist of objects with multiple properties. The JavaScript map() array function makes retrieving and displaying these properties in your JSX easier.


const students = [
  { id: 33, name: 'Khizer', score: 95 },
  { id: 34, name: 'Sachin', score: 85 },
  { id: 35, name: 'Hafsa', score: 30 },
];

const studenttList = students.map((student) => (
  <li key={student.id}>
    {student.name} - ${student.score}
  </li>
));

return (
  <ul>{studenttList}</ul>
);


In the above example, we have used the student.id as the key prop to access the student name and score properties within JSX. This allows us to display our data in a more structured and organized way.

Conditional Rendering and List Rendering Combined

At times, you will need to combine conditional rendering and list rendering. For instance, you have a list of grocery items. You can display the list with list rendering but can also visually indicate the non-available items with conditional rendering. Let's put it into the code for better understanding:


const grocery = [
  { id: 1, item: 'Flour', isAvailable: true },
  { id: 2, item: 'Milk', isAvailable: false },
  { id: 3, item: 'Salt', isAvailable: true },
  { id: 2, item: 'Blackpepper', isAvailable: false },
];

const groceryList = grocery.map((groceries) => (
  <li
    key={groceries.id}
    style={{ textDecoration: groceries.isAvailable ? 'line-through' : 'none' }}
  >
    {groceries.item}
  </li>
));

return <ul>{groceryList}</ul>;

When you render the above code, a list of grocery items will appear with a line-through over the unavailable items. Here, we have used the map() method to iterate through the list of groceries and groceries.id as the key prop. Then, we applied styling on the list of items based on the isAvailable prop. Once the new list (groceryList) has been formed, we have returned it.

Dynamic Rendering – Best Practices

While working with dynamic rendering, you should follow the following best practices:
• Avoid using overly complex conditions in your JSX, and try to keep them readable and straightforward. If necessary, break down the nested conditions into separate variables.
• Select a conditional rendering technique that best suits the complexity of your conditions. For instance, the ternary operator is well-suited for simple inline conditions, whereas if/else should be used for more complex logic.
• Always use unique and stable key props for predictable list rendering.

In this React tutorial for beginners, we have covered the basic concepts of React, including, but not limited to, installing and running React, creating components, rendering with JSX, using props, handling events, and conditional and list rendering. Hopefully, you have learned a lot in this tutorial. I highly recommend implementing all these concepts before moving to the advanced React tutorials.