Let's say I have a component, like:
<FormInput label="Phone Number" />
and I want to draw N number of them on the UI. What would the best practice for accomplishing this be? My initial thought is to create an array of N members so I can use map, like:
var myMapTrigger = [0,0,0,0,0]
myMapTrigger.map(function(){
return (<FormInput label="Phone Number" />)
}
This is of course a little hacky though.Is there a more idiomatic way that is more "thinking React"?
If you're open to using Lodash, then _.times
would work well.
_.times(N, i => <FormInput key={i} label="Phone Number" />);
(Don't forget to specify a key to make React happy.)
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.
This hack is pretty concise.
Array.from(Array(N)).map(() => {...})
Disclaimer: don't do this if N approaches infinity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With