1

I want to render multiple instances of the same component. Here is the component that will be repeated (not my actual component, just an example):

import React from 'react';

function Repeated () {
    return (
         <div></div>
    )
}

export default Repeated;

And the component that will repeat the other (again, just an example):

import React from 'react';
import Repeated from './Component1';

function OtherComp () {
    return (
         <div>
             <Repeated />
             <Repeated />
             <Repeated />
             <Repeated />
         </div>
    )
}

export default OtherComp;

Is there any way I can add the "Repeated" component multiple times through something like a loop, instead of having to copy and paste the component multiple times? Thanks :)

3 Answers 3

6

You can create a new array of desired length and map it to the components. However, you have to add a key to every one of them or ignore a warning:

With warning:

return (
  <div>
    {Array(4).fill(<Repeated />)}
  </div>
)

Mapping to keys:

return (
  <div>
    {Array(4).fill(true).map((_, i) => <Repeated key={i} />)}
  </div>
)
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @JakubKotrs after rendering 4 times, let's suppose we want only 3 then how can I delete 4th one, in the same
You can make the 4 be a prop. ({ number }) => ...
1

If you have an array for example and want to render each element as Repeat you can write

import React from 'react';
import Repeated from './Component1';

function OtherComp () {

    // get array via fetch or something else

    return (
         <div>
             { array.map(item => <Repeated key={a-unique-key} item={item} />) }
         </div>
    )
}

export default OtherComp;

Comments

1

You can loop through the array of props you want to render via the Repeated components, provided that each of the rendered components has a unique key The solution provided by @Jakub should work fine

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.