Home > Software design >  React generating components based on object prop number
React generating components based on object prop number

Time:01-08

I'm trying to generate components based off an objects files property which is a number. Every time I try, I get an error saying that the current parent component is getting too many children.

Assuming the files property is 5, does anyone know how to generate 5 divs per folder inside of the Grid item?

{folders.map((folder, index) => (
        <Grid item key={index} xs={4}>
          <CustomItem>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <CustomTypography>{folder.title}</CustomTypography>
              {/* <CustomTypography>{deck.message}</CustomTypography> */}
            </div>
            <Button
              onClick={() => handleDelete(folder._id)}
              sx={{
                position: "absolute",
                top: "10px",
                right: "0px",
                width: "10px",
              }}
            >
              <DoDisturbOnIcon />
            </Button>
            <Button
              onClick={() => handleAddFile(folder._id)}
              sx={{
                position: "absolute",
                top: "10px",
                left: "0px",

                borderLeftColor: "0px",
                width: "10px",
              }}
            >
              <AddCircleIcon />
            </Button>
          </CustomItem>
        </Grid>
      ))}

I'm basically trying something like this:

{for (let i = 0; i < folder.files   1; i  ) {
return <CustomItem>
}}

CodePudding user response:

You can use

{ 
  Array.from({length: folder.files }).map((_, i) => <CustomItem key={i} /> )
}
  • Related