I am trying to create a list of products using a set of data in react. I want to return the titles from this data and display it on screen in a list. I am trying to use a forEach loop but I'm. not sure exactly how to achieve this.
This is what I have so far:
import info from "./info";
import React from "react";
const ProductList = () => {
function listItems(item) {
return (
<Listbox.Option>
<Heading>{node.title}</Heading>
</Listbox.Option>
);
}
info.data.products.edges.forEach(listItems);
return listItems();
};
export default ProductList;
Can anyone tell me where I'm going wrong?
CodePudding user response:
Can you maybe simplify it so a version that looks like this:
import info from "./info";
import React from "react";
const ProductList = () => {
return info.data.products.edges.map((node) => (
<Listbox.Option>
<Heading>{node.title}</Heading>
</Listbox.Option>
));
};
export default ProductList;
Would this work for you ?
CodePudding user response:
Use map
evrytime you wanna render a list in React, like so:
import info from "./info";
import React from "react";
const ProductList = () => {
function listItems(item) {
return (
<Listbox.Option>
<Heading>{node.title}</Heading>
</Listbox.Option>
);
}
return (<div>{info.data.products.edges.map(item=>listItems(item))}</div>)
};
export default ProductList;
CodePudding user response:
You could do something similar to below:
var data = [
{
id: 1,
title: "Test1"
},
{
id: 2,
title: "Test2"
}
];
export default function App() {
return (
<ul>
{data.map((x) => {
return <li key={x.id}>{x.title}</li>;
})}
</ul>
);
}
You can run the code in the sandbox