Using conditions in an array map loop (Next.js)
P粉034571623
P粉034571623 2024-03-27 09:14:14
0
1
411

Final result UI

So I have this data

var arr = [1,2,3,4,5,6,7,8]

I want to check if the array index is a multiple of 5, so every time the loop is at index 0, 5, 10, etc. it will print this html <div class="slide-item"> <div>{data}</div></div> But when it is not at index 0, 5, 10, etc. (meaning it is at 1, 2, 3, 4, 6, 7, 8 etc.), it will print

<div class="slide-item"><div>{data 1}</div><div>{data 2}</div></div><div class="slide-item"><div>{data 3}</div><div>{data 4}</div></div>

So basically the final result UI is like the attached picture.

My first attempt was like this

{arr.map((res, index) => {return ({index % 5 === 0 ? (<div className="slide-item"><div>{res}</div></div>): (<div class="slide-item"><div>{data 1}</div><div>{data 2}</div></div>)}

I'm not quite sure how to do this, if anyone can help it would be greatly appreciated!

P粉034571623
P粉034571623

reply all(1)
P粉107991030

I think you need to check the condition based on res since the index always starts from 0

Try this

{
    arr.map((res, index) => {
        return ( res % 5 === 0 
            ? <div className="slide-item"><div>{res}</div></div>
            : <div>
                 <div class="slide-item"><div>{data 1}</div>
                 <div>{data 2}</div></div>
              </div>
         )       
     })
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template