example you have an array of products in data.js
const data = {
products: [
{
_id: '1',
name: 'Nike Slim Shirt',
category: 'Shirts',
image: '/images/p1.jpg',
price: 120,
countInStock: 10,
brand: 'Nike',
rating: 4.5,
numReviews: 10,
description: 'high quality product',
},
{
_id: '2',
name: 'Adidas Fit Shirt',
category: 'Shirts',
image: '/images/p2.jpg',
price: 100,
countInStock: 20,
brand: 'Adidas',
rating: 4.0,
numReviews: 10,
description: 'high quality product',
},
{
_id: '3',
name: 'Lacoste Free Shirt',
category: 'Shirts',
image: '/images/p3.jpg',
price: 220,
countInStock: 0,
brand: 'Lacoste',
rating: 4.8,
numReviews: 17,
description: 'high quality product',
},
{
_id: '4',
name: 'Nike Slim Pant',
category: 'Pants',
image: '/images/p4.jpg',
price: 78,
countInStock: 15,
brand: 'Nike',
rating: 4.5,
numReviews: 14,
description: 'high quality product',
},
{
_id: '5',
name: 'Puma Slim Pant',
category: 'Pants',
image: '/images/p5.jpg',
price: 65,
countInStock: 5,
brand: 'Puma',
rating: 4.5,
numReviews: 10,
description: 'high quality product',
},
{
_id: '6',
name: 'Adidas Fit Pant',
category: 'Pants',
image: '/images/p6.jpg',
price: 139,
countInStock: 12,
brand: 'Adidas',
rating: 4.5,
numReviews: 15,
description: 'high quality product',
},
],
};
export default data;
then you can use the code in app.js to iterate over this using map function like below, when you just type data inside curly braces, it should prompt you to import data.js in app.js.
Else you should manually import data.js like below:import data from "./data";
Note: when iterating over an array like below you should also include a unique key for each iteration element. this can be done like adding a key attribute to surrounding div element like:
<div key={product.slug}>
import {Link} from 'react-router-dom';
import data from "../data";
function HomeScreen(){
return <div><h1>Featured Products</h1>
<div className="products">
{
data.products.map(product=>(
<div key={product._id} className="product">
<Link to={/product/${product.slug}}>
<img src={product.image} alt={product.name} />
</Link>
<div className="product-info">
<Link to={/product/${product.slug}}>
<p>{product.name}</p>
</Link>
<p><strong>${product.price}</strong></p>
<button>Add to Cart</button>
</div>
</div>
))
}
</div></div>;
}
export default HomeScreen;
Leave a Reply