-1

Is there a simple way in React or JSX to create a number of copies of the same primitive element?

I know I can manually iterate over a n-length array to create copies like

[...Array(n).keys()].map(i => <td/>)

But is there a more elegant syntax for this simple task? Something like 3 * <td/> to make 3 empty cells in a row?

cebo
  • 688
  • 1
  • 8
  • 26
  • Its unclear exactly what you're trying to accomplish. Without more detail this question cannot be answered. It sounds like you're expecting too much from the syntax and should just write multiple tags, or build a function that returns a variable number of elements. – Brian Thompson Aug 27 '21 at 19:33
  • It's really as simple as I want a variable number of identical elements in a row, and I wanted to know if there was an existing construct to do that or if I'd need to do it manually. I couldn't find anything while searching for such a mechanism. – cebo Aug 27 '21 at 19:35
  • Are you just looking for [this](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx)? – David Aug 27 '21 at 19:35
  • That's roughly how I would do it manually. I just figured there might be a more elegant syntax for what seems like a simple operation – cebo Aug 27 '21 at 19:37

1 Answers1

2

You would need to do this manually. You can create an array of specific length and map it to the elements.

{Array.from({ length: 3 }, (_, i) => i).map(el => (
  <td key={el} />
))}

If this is something you find yourself doing often then abstract it into a component.

const Repeat = ({ count, child }) => {
  return Array.from({ length: count }, (_, i) => i).map((el) => (
    <React.Fragment key={el}>{child}</React.Fragment>
  ));
};

const Repeat = ({ count, child }) => {
  return Array.from({ length: count }, (_, i) => i).map((el) => (
    <React.Fragment key={el}>{child}</React.Fragment>
  ));
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Repeat count={3} child={<div>Hi</div>} />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    I used `[...Array(num).keys()].map(i => )` instead. It does the same thing and I find it way more readable, although I don't know if it's especially inefficient or something like that – cebo Aug 27 '21 at 20:53
  • 1
    @cebo I'm about 50/50 with both of these methods, depends on how I feel that day I guess. Performance-wise I don't think there's much difference. Cheers and good luck. – Drew Reese Aug 27 '21 at 20:53