0

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?

AlexTWO
  • 61
  • 6

2 Answers2

1

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

ANewGuyInTown
  • 5,957
  • 5
  • 33
  • 45
0

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 ?

Yasser hennawi
  • 735
  • 4
  • 10
  • The difference from your solution is, this line: `info.data.products.edges.forEach(listItems);` didn't really do anything except for looping over the elements, and since the return value of the forEach callback doesn't do anything, nothing happened and then you called `listItem()` without passing an argument to it, and it should take one, so you could remove the first line we discussed and then pass the items for your function like: `return listItems(info.data.products.edges);` but then the answer posted above would just look more simplified version of it. – Yasser hennawi May 20 '22 at 14:29