map() Function in React
The `map()` function is your best friend when working with lists in React. It's a JavaScript array method that creates a new array by transforming every element in an existing array. In React, we use it to transform data into JSX elements.
What is map()?
`map()` is a built-in JavaScript array method that calls a function on every element of an array and returns a new array with the results. It doesn't modify the original array.
In React, `map()` is the standard way to render lists because it perfectly fits React's declarative nature you describe how each item should look, and `map()` applies that to every item.
Basic map() Syntax
const numbers = [1, 2, 3, 4];const doubled = numbers.map(num => num * 2);<!-- doubled is [2, 4, 6, 8] -->Using map() in React
function NumberList() { const numbers = [1, 2, 3, 4, 5];
return ( <ul> {numbers.map(number => ( <li key={number}>{number}</li> ))} </ul> );}map() with Object Arrays
function BookList() { const books = [ { id: 1, title: 'React Basics', author: 'John Doe' }, { id: 2, title: 'Advanced React', author: 'Jane Smith' }, { id: 3, title: 'React Hooks', author: 'Bob Johnson' } ];
return ( <div className="book-list"> {books.map(book => ( <div key={book.id} className="book-card"> <h3>{book.title}</h3> <p>by {book.author}</p> </div> ))} </div> );}map() with Index Parameter
The callback function in `map()` can also receive the current index as a second parameter:
function TodoList() { const todos = ['Wake up', 'Eat breakfast', 'Code'];
return ( <ul> {todos.map((todo, index) => ( <li key={index}>{index + 1}. {todo}</li> ))} </ul> );}map() with Conditional Logic
function ProductList({ products }) { return ( <div> {products.map(product => ( <div key={product.id}> <h3>{product.name}</h3> {product.discountedPrice ? ( <p>Sale: ${product.discountedPrice} <del>${product.price}</del></p> ) : ( <p>Price: ${product.price}</p> )} </div> ))} </div> );}Chaining map() with filter()
function ActiveUsers({ users }) { return ( <ul> {users .filter(user => user.isActive) .map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> );}map() with Fragments
If you need to return multiple elements per item without adding extra nodes to the DOM, use fragments:
function ProductDetails({ products }) { return ( <div> {products.map(product => ( <React.Fragment key={product.id}> <h3>{product.name}</h3> <p>{product.description}</p> </React.Fragment> ))} </div> );}Two Minute Drill
- `map()` is a JavaScript array method that transforms every element and returns a new array.
- In React, we use `map()` to convert arrays of data into arrays of JSX elements.
- Always provide a unique `key` prop to the elements returned by `map()`.
- The callback function can take the current item and its index as parameters.
- You can chain `filter()` and `map()` to render subsets of data.
- `map()` is fundamental to dynamic rendering in React master it!
Need more clarification?
Drop us an email at career@quipoinfotech.com
