1

I am trying to render a dynamic list of elements using React, i.e. I have a javascript array elems = ['foo','bar'] and I would like to generate

<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

I would like to do this purely in JSX. Is there any convenient way to do this (an "equivalent" of angular ng-repeat)?

jfu
  • 1,700
  • 1
  • 22
  • 31
  • possible duplicate of [loop inside React JSX](http://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – Felix Kling Jul 08 '15 at 08:24

2 Answers2

4

The beauty of React/JSX is that you basically just write JavaScript. So if you have a list of things and want to create a list of components, just map the list:

<ul>
  {items.map(item => <li>{item}</li>)}
</ul>

(and it's also really concise with arrow functions)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Does the child always have to be an Array? Is there any way to say `var ul =
      ` and `var li =
    • ` then somehow appendChild to ul before returning it? – neaumusic Jul 22 '16 at 21:56
  • I think you can only add children to an existing React element by using `React.cloneElement`. But you can write `var ul =
      {li}
    ;` or `var ul =
    ;`.
    – Felix Kling Jul 23 '16 at 08:06