Home > Enterprise >  Rendering Multiple Instances of the Same Component - React
Rendering Multiple Instances of the Same Component - React

Time:04-14

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 :)

CodePudding user response:

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>
)

CodePudding user response:

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;

CodePudding user response:

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

  • Related