React js Mapping
data Mapping() in HTML Table Tag at React js
To create a data table in React that maps over an array of data, you can follow these steps:
- Prepare the Data: Use an array of objects, where each object represents a row in the data table.
- Map Over Data: Use the
.map()function to dynamically generate table rows. - Use a Functional Component: Render the table with a reusable component, which is a best practice in React.
Here’s a basic example:
import React from 'react';
export default function App() {
// Sample data array of objects
const data = [
{ id: 1, name: 'Alice', age: 25, email: 'alice@example.com' },
{ id: 2, name: 'Bob', age: 30, email: 'bob@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', age: 35, email: 'charlie@example.com' },
// Add more data as needed
];
return (
<table border="1" style={{ width: '100%', textAlign: 'left' }}>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{data.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.email}</td>
</tr>
))}
</tbody>
</table>
);
};
Explanation
- Data Structure: The
dataarray contains objects, each with propertiesid,name,age, andemail. - Table Header:
<thead>defines static table headers. - Mapping Rows: In
<tbody>,data.map()iterates over the array, generating a<tr>for each object. - Unique Keys:
key={item.id}helps React efficiently update the table when the data changes.