Alex
Alex

Reputation: 2800

How to create multiple empty elements inline with React

What is the best way to create multiple empty elements inline using React within render in a declarative fashion?

For example, say I wanted 8 empty divs, the following was my first attempt although it doesn't work, is there a better way?

render() {
    return (
        <section>
            {
                new Array(8).map(()=> <div />)
            }
        </section>
    );
}

Upvotes: 1

Views: 1029

Answers (3)

Jonas Wilms
Jonas Wilms

Reputation: 138557

I'd use a small helper for it:

  const times = (length, fn) => Array.from({ length }, (_, i) => fn(i));

To be used as:

 times(8, i => <div key={i} />)

Upvotes: 4

Keith
Keith

Reputation: 24241

As seen the simplest option is just Array(8).fill().map(<div />)

But one issue with the above is your creating an array to make another array. It's not a massive issue, but if you like modern JS, a nice solution is iterators. And of course iterators can be used for other things, not just arrays.

Below is an example.

function *range(r, map) {
  for (let l = 0; l < r; l += 1) yield(map ? map(l) : l);
}

const a1 = Array.from(range(3));
const a2 = Array.from(range(3, m => 2 + m * 2));

console.log(a1);
console.log(a2);

//and of course not just arrays
for (const value of range(3)) console.log(value);

Upvotes: 1

Mike Duister
Mike Duister

Reputation: 260

You'd have to fill the array first:

export default class Example extends React.Component {
    render() {
        return (
            {Array(8).fill(null).map((item, index) => (
                <div key={index}/>
            )}
        )
    }
}

Upvotes: 2

Related Questions