Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for generating N of a component in React (without data)

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

like image 650
Thomas Murphy Avatar asked Jun 16 '16 15:06

Thomas Murphy


3 Answers

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.)

like image 56
Josh Kelley Avatar answered Sep 28 '22 22:09

Josh Kelley


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 &amp; 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.

like image 27
Alex Ruble Avatar answered Sep 28 '22 20:09

Alex Ruble


This hack is pretty concise.

Array.from(Array(N)).map(() => {...})

Disclaimer: don't do this if N approaches infinity.

like image 32
Alexandru Kis Avatar answered Sep 28 '22 21:09

Alexandru Kis