Home > Net >  how to return list inside for loop without breaking
how to return list inside for loop without breaking

Time:11-03

I have a list of elements and I would like to print 3 of them in cards in every row.

the problem with the following code : it prints just the first two elements and the loop stops.

here's my code im using reactjs and mui :

const testList = [//my list]

const ListInvoices = (props) => {

const invoicesList = () => {

  for(let i = 1; i <= testList?.length; 3*i){
      let invList = testList?.slice(i-1, 2*i)
      return(
         <Grid container alignItems="center" justifyContent="center">
            <div style={{ display: "flex", flexDirection: "row" }}>
            {invList ?.map((elt, index) => {
               return(
                 <Grid item>
                     <Card sx={{m: 2}} key={{index}}>
                        {/* content of card */}
                     </Card>
                 </Grid>
               )
             })
            }
            </div>
         </Grid>
      )
  }
}

return(
  <Box sx={{ backgroundColor: "#f6f6f6" }} pt={4} pb={4}>
     <Container maxWidth="lg">
         {invoicesList()}
     </Container>
  </Box>
)
}

thank you in advance

CodePudding user response:

Here is the relevant info for your problem Loop inside React JSX But could the problem be when you multiply i by 3,

for(let i = 1; i <= testList?.length; 3*i <-- here

Because when i = 1, i * 3 = 3, but when i = 3, i * 3 = 9, so it would skip the second row.

CodePudding user response:

I'm not sure if I got your problem right. However, I do see why this line

invList ?.map((elt, index) => {

returns only 2 cards. I assume it's here where it had to return 3? If so, maybe I have an answer for you.

Mind that when using slice, the end index will not be included.

When applying the following code (extracted from yours):

let invList = testList?.slice(i-1, 2*i)

If index is 1 and the we have an array as the following one:

[0, 1, 2, 3, 4, 5]

invList will slice from 0 (index - 1) to 1, since 2 (2 * 1) will be the end index that is not included.

Therefore, the third number should be printed with the following small change:

let invList = testList?.slice(i-1, 3*i)

or

let invList = testList?.slice(i-1, 2*i   1)

Having said so, is there any specific reason as of why you are using a for loop? I believe it could be replaced with map, using the second parameter passed at each iteration (the index parameter).

  • Related