- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React Lists
- React lists allow you to render a collection of elements dynamically based on data.
- Since React doesn't have a specific "loop" directive (like
v-forin Vue or*ngForin Angular), it relies on standard JavaScript methods to iterate through arrays. - They provide a way to map over an array and generate JSX components for each item, making it easy to display data from APIs or local state.
map(), you are essentially transforming an array of data into an array of UI elements that React can paint to the screen.
Rendering a Simple List
In React, the map() function is the industry-standard way to transform a data array into a list of elements. Here is how you can render a basic list of strings.
import React from 'react';
const SimpleList = () => {
const fruits = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
};
return the JSX inside the map() function. If you use curly braces { } instead of parentheses ( ) after the arrow, you must explicitly write the return keyword, or nothing will render.
Rendering Lists of Components
In most professional applications, you won't just be mapping over strings. You’ll usually deal with an array of objects fetched from a database. Each object typically has a unique identifier (like an id).
import React from 'react';
const UserList = () => {
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
key prop. This ensures that React can track each item accurately if the list is re-sorted, filtered, or updated.
Adding Keys to List Items
- Providing a unique key to each list item helps React’s "Reconciliation" process. This is how React determines which items have changed, been added, or been removed.
- Without keys, React might re-render the entire list instead of just the specific item that changed, which hurts performance.
index as a key is considered a "last resort." If your list can be reordered or items can be deleted, using the index can cause bugs in your UI, such as form inputs showing the wrong data or incorrect animations.
Conditional Rendering in Lists
Sometimes you only want to show specific items from a list. You can use logical operators like && or the filter() method before mapping to control what gets displayed.
import React from 'react';
const FilteredList = () => {
const numbers = [1, 2, 3, 4, 5];
return (
<ul>
{numbers.map((number) => (
number % 2 === 0 && <li key={number}>{number}</li>
))}
</ul>
);
};
const evens = numbers.filter(n => n % 2 === 0); then map over evens.
Handling List Events
Interactive lists are a staple of modern web apps. You can attach event listeners (like onClick) to each item in the list and pass the item's data back to a handler function.
import React, { useState } from 'react';
const ClickableList = () => {
const [selectedItem, setSelectedItem] = useState(null);
const items = ['Item 1', 'Item 2', 'Item 3'];
const handleItemClick = (item) => {
console.log(`You clicked on: ${item}`);
setSelectedItem(item);
};
return (
<ul>
{items.map((item, index) => (
<li
key={index}
onClick={() => handleItemClick(item)}
style={{
cursor: 'pointer',
fontWeight: selectedItem === item ? 'bold' : 'normal',
color: selectedItem === item ? 'blue' : 'black'
}}
>
{item} {selectedItem === item && '(Selected)'}
</li>
))}
</ul>
);
};
onClick={() => handleClick(item)}. This prevents the function from executing immediately when the component renders.
Summary
Working with lists is a fundamental aspect of building dynamic and responsive React applications. By leveraging the map() method, you can transform raw data into interactive user interfaces effortlessly. Remember that keys are the secret sauce that keeps React fast—always try to use stable, unique IDs to ensure your application remains performant and bug-free as it grows.