Reputation: 1160
I'm following a beginners React tutorial and I'm having an issue with this:
import React from "react";
import productsData from "./productsData";
import Product from "./Product";
function App() {
const productComponents = productsData.map(product => {
<Product key={product.id} product={product} />
})
return(
<div>
{productComponents}
</div>
)
}
export default App;
The imported value productsData
is just a JSON-style array of objects. If I put a debugger in before the map then productsData
throws a not defined error. Yet if I do this:
import React from "react";
import productsData from "./productsData";
import Product from "./Product";
function App() {
return(
<div>
<Product product={productsData[0]} />
</div>
)
}
export default App;
Then it correctly displays the component based on the first object in the array.
Furthermore, in the debugger, there is a module named _productsData__WEBPACK_IMPORTED_MODULE_1__
which contains the array I'm after, among other things.
My question is why can't I just access productsData
?
Upvotes: 1
Views: 205
Reputation: 96
I believe in the first instance you are missing a return statement within your map function. Since you have the map function in brackets, Javascript is looking for something to be returned to the array that the map function returns into productComponents
.
The reason the second example works for you, is due to the fact that you are correctly returning the component.
I believe something like the below should work for you.
** Note the return keyword before your component.
const productComponents = productsData.map(product => {
return <Product key={product.id} product={product} />;
});
Upvotes: 3