1

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!

1

2 Answers 2

3

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

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}
        </>
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.