Mellisa
Mellisa

Reputation: 605

Seperator in map on JSX using index

I want to skip a <hr /> in the end, so I added condition using index and the length of the array, like this

{item.persons.map((item,i) => 
    <div>
        <p>Name: {item.name}</p>
    {i !== item.persons.length ? <hr /> : ''}
    </div>
)}

Any clue why this doesn't work? I can leave the <hr /> like this

{item.persons.map((item,i) => 
    <div>
        <p>Name: {item.name}</p>
    <hr />
    </div>
)}

but this looked broken as it will has hr after the last item too.

Upvotes: 1

Views: 52

Answers (1)

C&#233;sar Landesa
C&#233;sar Landesa

Reputation: 2656

You should bear in mind that the last item is not the one with index length but length-1

var persons = ["A", "B", "C"]

{persons.map((item,i) => 
   {i !== (persons.length-1) ? console.log(item) : console.log("LAST")}
)}

Upvotes: 2

Related Questions