Reputation: 688
I have a .map()
function on an array.
When I do a console.log(object)
inside the .map it logs the object.
But when I do <li key={key}>{object.name}</li>
it shows nothing.
Also not in the inspection tool.
Component:
<StyledImagesList>
{this.state.images.map((imageObject, key) => {
// <img src={imageObject.contentUrl} title={imageObject.name} />
<li key={key}>{imageObject.name}</li>
{console.log(imageObject)}
})}
</StyledImagesList>
StyledImagesList has no styling
export const StyledImagesList = styled.ul;
Any idea why my li
's won't be visible?
Upvotes: 3
Views: 1196
Reputation: 2610
Map()
uses return
in it's code block in order to push each elements to a NEW array. It doesn't touch the original one.
The code you do inside the loop does run in fact... It's just that you didn't got any thing in return to show.
Doing
return <li key={key}>{imageObject.name}</li>
will build you a new array with those html elements for you.
The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Note: map() does not execute the function for array elements without values.
Note: map() does not change the original array.
Upvotes: 0
Reputation: 30360
Returning the <li>
element in your map()
callback should resolve the issue:
<StyledImagesList>
{ this.state.images.map((imageObject, key) => {
// <img src={imageObject.contentUrl} title={imageObject.name} />
/* Logging would need to happen before the return */
console.log(imageObject);
/* Add return here */
return <li key={key}>{imageObject.name}</li>
}) }
</StyledImagesList>
If logging to console were not needed, you could achieve the same result with the more concise equivalent of:
<StyledImagesList>
{ this.state.images.map((imageObject, key) => <li key={key}>{imageObject.name}</li>) }
</StyledImagesList>
Upvotes: 2
Reputation: 14669
Return is missing. Either
this.state.images.map((imageObject, key) => {
return <li key={key}>{imageObject.name}</li>;
})
or
this.state.images.map((imageObject, key) => (
<li key={key}>{imageObject.name}</li>
))
Upvotes: 2