React/JSX: Simply create n copies of the same element? [closed]

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?

Answer

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" />