ForEach over es6 Map in JSX

I had a javascript array that handled components with array.map. I switched this array to es6 Mapin order to be able to use key-value pairs for a more convenient search for elements and switch from .mapto forEachthe map. Internally, forEachI call a rendering method that returns a React component, but it does not appear. How to visualize a component inside forEach?

<div className='gallery__items'>
    {resultsByGuid.forEach((result, index) => {
        key++;
        this.renderGalleryItem(result, key);
    })} 
</div>

Here is the renderGalleryItem method:

renderGalleryItem = (item, index) => {
    const { gridItemSelected, itemThumbnailRequested } = this.props;
    return (<GalleryItem key={index}
        item={item}
        onClick={gridItemSelected}
        fetchThumbnailFunc={itemThumbnailRequested}
    />);
};

I understand that forEach does not return anything, but does this mean that I cannot display inside it?

+4
source share
4 answers

, forEach , map , JSX.

: resultsByGuid.map((item, key) => { })

, , map. forEach , , Array.map :

const mapIterator = (map, cb) => {
  const agg = [];
  for(let [key, value] of map) {
    agg.push(cb(value, key));
  }
  return agg;
};

<div className='gallery__items'>
  {mapIterator(resultsByGuid, (result, index) => {
    key++;
    return this.renderGalleryItem(result, key);
  })}
</div>

2 @zerkms , :

<div className='gallery__items'>
  {Array.from(resultsByGuid.values()).map((result, index) => {
    key++;
    return this.renderGalleryItem(result, key);
  })}
</div>
+5

, options - es6 Map()..

<select>
  {
    [...options].map((entry) => {
      let key = entry[0]
      let value = entry[1]
      return <option key={ key } value={ key }>{ value }</option>
    })
  }
</select>
+2

.entries() , , / : [key, value]

, :

<div className='gallery__items'>
  {resultsByGuid.entries().map((result) => {
    return this.renderGalleryItem(result[1], result[0]);
  })}
</div>

, .

+1
source

Just a small improvement on the example of danday74 using array destruction. With options for ES6 card:

<select>
  {
    [...options].map(([key, value]) => {
      return <option key={ key } value={ key }>{ value }</option>
    })
  }
</select>
0
source

All Articles