Displaying array elements from Map

I need some help displaying the elements from map. I stored all the names into a new array and want to display this data using html/css.

    const playlistName = playlists.map(playlist => {
    return playlist.name
})

    <ul className={modalStyles.playlist_container}>
    <li className={modalStyles.playlist_item}>{playlistName}</li>
   </ul>

If I do something like this it’ll display all the names on one li which doesn’t make sense since I only have 1 li and makes it really hard to position with css. It’ll end up looking like this:

name1name2name3name4

I know I can display every individual element with playName[0] but I also I have to consider if the array is really big. Is there a way I can display every element with spacing like this?

name1          name2          name3           name4       name...

Answer

It looks like youre using React. You would want to wrap playlist.name in a <span></span> and style the span with some padding or margin.

So it might look like:

    const playlistName = playlists.map(playlist => {
        return <span className="mySpan">{playlist.name}</span>
    })

Then you can target and style the span:

.mySpan{
    margin-right: 10px;
}

Though you probably want each in it’s own <li>, in which you’d probably want to return those instead:

    const playlistName = playlists.map((playlist, index) => 
        <li key={index}>{playlist.name}</li>
    })

Leave a Reply

Your email address will not be published. Required fields are marked *