List Rendering in React

List Rendering in React

In React, you can use a list rendering technique when you want to render a list of items based on an array of data. This can be useful when you have a collection of data that you want to display in a specific order or when you want to render a list of items that may change over time.

To use list rendering in React, you can use the map() function to iterate over the items in the array and return a JSX element for each item. For example, consider the following array of names:

const names = ['Alice', 'Bob', 'Charlie', 'David'];

You can use the map() function to render a list of <h2> elements for each name in the array like this:

{names.map(name => <h2 key={name}>{name}</h2>)}

This will result in a list of names being rendered on the page, with each name being wrapped in a <h2> element.

It's important to note that when rendering lists of elements in React, you should include a key prop for each item in the list. This helps React identify each item in the list and optimize the rendering process.

Now, suppose you want to render elements inside an array which is again inside an array. For example :

const persons = [
        {
            id: 1,
            name: 'Bruce',
            age: 32,
            skill: 'React'
        },
        {
            id: 2,
            name: 'Clark',
            age: 28,
            skill: 'Angular'
        },
        {
            id: 3,
            name: 'Diana',
            age: 35,
            skill: 'Vue'
        }
 ]

Suppose you want to render it like this :

I am (Name) and I am (Age) years old. I am good at (Skills).

You can render it in the following way :

persons.map(person => <h2 key={person.id}> I am {person.name} and I am {person.age}. I am good at {person.skill}. </h2>)

Here, we are passing the ID of the person in the key props as it is a unique property.