3

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?

2
  • 7
    you need to return something in a map Commented Apr 12, 2019 at 11:49
  • @JaromandaX but ofcourse... Thanks for the help ;) Commented Apr 12, 2019 at 11:53

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

There is a shortcut here for logging => console.log(imageObject) || <li key... because the log is a Falsy return.
Nice! Thanks for that , this could come in handy 😊
2

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>
    ))

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.