Two years later, here's the most parsimonious way I know of to make an array containing n
elements in native JS.
const duplicate = (x, n) => Array.from(new Array(n), () => x);
const n = 3;
const oneComp = <span>Unicorns & Rainbows</span>;
const nComps = duplicate(oneComp, n);
class FormInputGroup extends React.Component {
// ...
render() {
// ...
return <div>{nComps}</div>;
}
// or, in this case,
render = () => <div>{nComps}</div>;
}
// or even
const ComponentGroup = () => <div>{nComps}</div>;
// renders as "Unicorns & RainbowsUnicorns & RainbowsUnicorns & Rainbows"
In case you're wondering why not just use new Array(n)
, it's because that expression has length n
, but contains 0 elements — i.e.
const trashArray = new Array(n);
console.log(trashArray.length) // prints `n`
console.log(Object.keys(trashArray)) // prints `[]`
— this means that trashArray.map(func)
will always yield an empty array (but one with .length = n
, thanks JavaScript).
(If they're inline and you want to put, say, <br />
s between them but not after the last one, you can do something like
const zipInLineBreaks = tags => tags.reduce((accum, currentEl, i, arr) => accum
.concat([currentEl]) // or, in this case, `[oneComp]`
.concat((i === arr.length - 1)
? []
: [<br /]
), []);
const children = zipInLineBreaks(nComps);
Group = () => <div>{children}</div>;
/*
* "Unicorns & Rainbows
* Unicorns & Rainbows
* Unicorns & Rainbows"
*/
.)
See this sandbox for an example where the repeated element is a React Component.