08 Reusable Components - biswajitsundara/react GitHub Wiki
Often we will come across reusable/repeated components
- Like we want to display our data in form of a list, table row, card deck etc.
- So we need to iterate over the data and create component dynamically.
We will use the below data for all examples. Place it in Data.js
file
export const citiesData = [
{
id: "london",
name: "London",
country: "United Kingdom",
population: 125000,
},
{
id: "san-fransisco",
name: "San Fransisco",
country: "United States Of America",
population: 225000,
},
{
id: "delhi",
name: "New Delhi",
country: "India",
population: 725000,
},
];
Let's take a simple example, we want to display a list of data using a loop.
import { citiesData } from "./Data";
const DataList = () => {
//Approach 1 using loop
const citiesList = [];
for (let i = 0; i < citiesData.length; i++) {
const city = <li>{citiesData[i].name}</li>;
citiesList.push(city);
}
return (
<>
<ul>{citiesList}</ul>
</>
);
};
export default DataList;
We can do the same thing using the array map method.
- We can also place the map method directly between the
ul
tags - If you check the console, you will see errors.
- React will complain all child elements should have unique keys.
import { citiesData } from "./Data";
const DataList = () => {
//Approach 2 using map
const citiesList1 = citiesData.map((city) => <li>{city.name}</li>);
//Approach 3 using map with key
const citiesList2 = citiesData.map((city) => (
<li key={city.id}>{city.name}</li>
));
return (
<>
<ul>{citiesList1}</ul>
<ul>{citiesList2}</ul>
</>
);
};
export default DataList;
Here we have good reasons to split the components.
- Let's have the list item in a separate component.
//CityItem.jsx
const CityItem = ({ city }) => {
return (
<ul>
<li>Name: {city.name}</li>
<li>Country: {city.country}</li>
<li>Population: {city.population}</li>
</ul>
);
};
export default CityItem;
//Cities.jsx
import CityItem from "./CityItem";
import { citiesData } from "./Data";
const Cities = () => {
const citiesList = citiesData.map((city) => (
<CityItem city={city} key={city.id} />
));
return <div>{citiesList}</div>;
};
export default Cities;