0

I'm trying to figure out a way to use a loop to create multiple instances of a react component. Something like this:

export default function Squares() {

  return (
    <>
    {for(let i = 0;i < 25;i++) {
      <ReactComponent />
    }}
    </>
  )
}

This doesn't obviously work, but this is the general idea of what I'm trying to accomplish. Thank you for any help in advance!

CodyLee
  • 81
  • 1
  • 5

2 Answers2

2

Just put them in an array.

export default function Squares() {
  const children = [];  
  for(let i = 0;i < 25;i++) {
    children.push(<ReactComponent />);
  }

  return children;
  // or
  return (
    <SomeWrapperComponentOrFragment>
      {children}
    </SomeWrapperComponentOrFragment>
  );
}
GitGitBoom
  • 1,822
  • 4
  • 5
2

Remember to add key value for each component. As well use shrink fragment as you are correctly doing. But abstract logic code outside of return.

export default function Squares() {
    const generateList = (max=1) => {
        const arr = [];
        for (let i = 1; i < max; i++) {
            arr.push(<ReactComponent key={`id-${i}`} />);
        }
    };

    return (
        <>
            {generateList}
        </>
    );
}
Eddwin Paz
  • 2,842
  • 4
  • 28
  • 48