React Design Patterns and Best Practices(Second Edition)
上QQ阅读APP看书,第一时间看更新

Loops

A very common operation in UI development is to display lists of items. When it comes to showing lists, using JavaScript as a template language is a very good idea.

If we write a function that returns an array inside our JSX template, each element of the array gets compiled into an element.

As we have seen before, we can use any JavaScript expressions inside curly braces, and the most common way to generate an array of elements, given an array of objects, is to use map.

Let's dive into a real-world example. Suppose you have a list of users, each one with a name property attached to it.

To create an unordered list to show the users, you can do the following:

  <ul> 
{users.map(user => <li>{user.name}</li>)}
</ul>

This snippet is incredibly simple and incredibly powerful at the same time, where the power of the HTML and JavaScript converge.