Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 5249  / 2 Years ago, wed, april 13, 2022, 12:00:00

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


More From » reactjs

 Answers
22

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

[#195] Monday, April 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
armandoh

Total Points: 208
Total Questions: 94
Total Answers: 112

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
armandoh questions
Sat, Jan 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Sun, Dec 22, 19, 00:00, 5 Years ago
Wed, Apr 10, 19, 00:00, 5 Years ago
;