Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a <div> only once while looping and displaying other data in a loop

I have a use case where am displaying options with the help of a loop.

I need to display the text suggestions only once for the entire loop cycle. The code block number.imageUrl may repeat but the suggestions text should be displayed only once.

const listItems = numbers.map((number) => 

<li>

{number.imageUrl && 

<div>suggestions</div>

<div>{number.imageUrl}</div>

}
<div>number.text</div>

</li>

);
like image 575
Shaik Taher Avatar asked Oct 14 '25 05:10

Shaik Taher


1 Answers

Like Justinas said, either move <div>suggestions</div> out of the map function, or do this:

const listItems = numbers.map((number, index) => (
  <li>
    {index === 0 && <div>suggestions</div>}
    {number.imageUrl && <div>{number.imageUrl}</div>}
    <div>{number.text}</div>
  </li>
));
like image 192
tomleb Avatar answered Oct 16 '25 17:10

tomleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!