I am trying to use a higher order function to get information from another file. I have three files that i use. My SchoolProduct.js file which is an array with objects, Second is my Product.js component. This file i am using for Props . Third file App.js where the magic should happen. I keep getting an error. 'product' is defined but never used. I know well what it means but i keep looking into my code without any luck. I want to display all the object elements to the screen, its very simple. heres my code.
App.js file
import React from 'react'
import SchoolProducts from "./SchoolProducts.js"
import Product from "./component/Product.js"
function App() {
const OurProducts = SchoolProducts.map(
Product => <Product key={"1"} name={Product.name} description={Product.description}/>
)
return (
<div>
{OurProducts}
</div>
)
}
export default App;
Product.js file
import React from "react"
function Product(props) {
return (
<div>
<h3>{props.Product.name} </h3>
<h3> {props.Product.price}</h3>
<h3> {props.Product.description}</h3>
</div>
)
}
export default Product
SchoolProducts.js file
const SchoolProducts = [ {
id: "1",
name: "pencil",
description: "Perfect for those who cant remember things"
},
{
id: "2",
name: "pencil",
price: 1,
description: "Perfect for those who cant remember things"
},
{
id: "3",
name: "pencil",
price: 1,
description: "Perfect for those who cant remember things"
},
{
id: "4",
name: "pencil",
price: 1,
description: "Perfect for those who cant remember things"
},
{
id: "5",
name: "pencil",
price: 1,
description: "Perfect for those who cant remember things"
}
]
export default SchoolProducts
You're using the same variable name in different scopes - the Product
on the top level is the React component, but the SchoolProducts
contains the array of objects, so with SchoolProducts.map(Product =>
, inside that .map
, Product
refers to a plain object.
Use different variable names:
const OurProducts = SchoolProducts.map(SchoolProduct => (
<Product key={"1"} name={SchoolProduct.name} description={SchoolProduct.description}
/>
));
Or destructure immediately:
const OurProducts = SchoolProducts.map(({ name, description }) => (
<Product key={"1"} name={name} description={description}
/>
));
(you can avoid making these sorts of mistakes by enforcing the no-shadow ESLint rule)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.