G
G
gomerIT2020-12-19 01:12:06
JavaScript
gomerIT, 2020-12-19 01:12:06

ReactJS should use forEach instead of map in this situation?

I am passing an array of objects to the component.
products = [{...},{...},{...}]

function GameProducts({products}) {
  products.map((items) => {
     <GameProduct product={items} />
  });
}

function GameProduct({product}) {
     const {img, title, desc, price, date} = product;
    // ... рендеринг
}

I don't quite understand the difference between map and forEach yet. Map should return something as a function, in the example I essentially return jsx, right, or is forEach still suitable here? I just don't want to shit

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
n1ksON, 2020-12-19
@n1ksON

This code won't work because it doesn't return anything.

products.map((items) => {
     <GameProduct product={items} />
  });

Either do this => ({}), or do this =>:
products.map(items => 
     <GameProduct product={items} />
);

If you have an array of objects that contain information about repeating blocks, then it will be correct to use the map method. What you are doing is correct.
The forEach method is usually used to perform complex logic related to changing/transforming an array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question