How to render the same component 5 times? (clone component) Please tell how to render the same component 5 times in render. I have 5 the same forms.
Asked
Active
Viewed 1,436 times
0
-
3Possible duplicate of [How to repeat an element n times using JSX](https://stackoverflow.com/questions/34189370/how-to-repeat-an-element-n-times-using-jsx) – Michael Jasper Aug 05 '18 at 16:33
-
Don't "render the same component" multiple times, just _generate_ five components off of the data that generates your components. Also, if you have the same form five times, ask yourself why you're trying to put them all on the same page/view at the same time. That sounds like terrible UX for the user. – Mike 'Pomax' Kamermans Aug 05 '18 at 16:36
-
I have 5 forms with the same fields (email and login). – DFGD Aug 05 '18 at 16:46
1 Answers
1
You can use Array.from
to create as many copies of a component as you want.
Example
function MyComponent() {
return <div> MyComponent </div>;
}
function App() {
return (
<div>
{Array.from({ length: 5 }, (_, index) => <MyComponent key={index} />)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Tholle
- 108,070
- 19
- 198
- 189
-
Do note that, normally, using the array index as key is a terrible idea, because it completely undoes React's smart diffing. If you absolutely _must_ take this approach, then those keys are fine, but a better solution is to model your UI as components, and simply place new components where needed. If you're cloning like this, you're effectively saying "I have no idea why I'm rendering my UI this way", which is... questionable? – Mike 'Pomax' Kamermans Aug 05 '18 at 16:38
-
Yes, if you e.g. have a unique id for every element in an array you want to render that is much better to use as `key`, but if the order of an array will not change it's fine to use the index. ["When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort"](https://reactjs.org/docs/lists-and-keys.html). – Tholle Aug 05 '18 at 16:41
-
-
@cbdev420 The first argument given to the function is the element, but since that 's not used I named it `_`. You can name it whatever you like. – Tholle Apr 08 '19 at 17:11