It is a common requirement to display the same UI element for different sets of data. For example, social media posts, lists of users, product lists on an e-commerce website, and so on.
Let's see a simple implementation of displaying a list of users.
In the above example, we can see that the same component, i.e., User, is being used for different data.
In most real-life cases, we will have to render components dynamically from an array of data received from APIs. In such cases, we can use the map
method from JavaScript to generate an array of elements from the data.
Let us try to simulate such a situation by extracting the data into a constant in the above example and then applying map
to it.
Step 1. Move the data into an array of objects:
Step 2. Map the records of USERS
array into a new array of JSX nodes:
For each user
object, a JSX element is created, and the resulting array contains a list of JSX nodes of User
component that can be rendered in a React component to display the list of users.
Step 3. Return the mapped array of JSX nodes from the App
component.