I’m trying to render the props in a loop (a forEach function), but I haven’t figure out how to 🙁
This is what I have so far:
{console.log('the catalog inside the component ----->', catalog)}
{Object.keys(catalog).forEach(key => {
return (
<div className='flex flex-col'>
<p className='ml-12 mt-12'>`${key}`</p>
<div className='flex justify-center items-center flex-wrap'>
{catalog[key].forEach(item => {
return (
<Image src={`/${key}/${item}`} width={150} height={150} alt={`${item}`} onClick={enlarge} className='cursor-zoom-in m-4' />
)
})}
</div>
</div>
)
})}
<p>{catalog.Marca1[0]}</p>
Here’s what the catalog looks like:
the catalog inside the component -----> {
Marca1: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
Marca2: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
Marca3: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ],
Marca4: [ 'gafas1.png', 'gafas2.png', 'gafas3.png', 'gafas4.png' ]
}
The last line does render in the page. I just added it for testing:
<p>{catalog.Marca1[0]}</p>
The whole project is here:
https://github.com/Tezcatlipoca0000/paver
I am teaching myself how to code, so I will have a lot of mistakes.
Any help would be greatly appreciated.
Thanks in advance 🙂
2
Answers
Array#forEach
returnsundefined
. UseArray#map
instead to transform an array.That is because foreach does not return values (it returns undefined):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#return_value
You have to change the forEach method with map method which returns an array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#return_value
Code: not tested, only modify forEach methods with map methods