Skip to main content

How to Map Components in React

In our previous tutorial, we have listed Best PDF Viewer Component for React. In this tutorial, we will explain about Mapping Components in React.

As the React takes regular JavaScript data and turn into HTML, so here we will see how easily we can turn our array data into HTML elements.

Suppose you have employee list in an array and wants to turn that into <li> elements. The map() function from JavaScript do the magic to achieve our goal. It will help to loop through array and create new HTML elements for each record in an array. It will help to display elements like this.

Also, read:

function displayEmployee() {
    return (
        <ul>
            {[<li>Smith</li>,<li>William</li>,<li>Andy</li>]}
        </ul>
    )
}

So we have an employee array and wants to display details.

const employee = [
	{
		name: "Smith",
		country: "France"		
	},
	{
		name: "Danial",
		country: "Germany"
	},
	{
		name: "William",
		nickName: "Australia"
	},
	{
		name: "Andy",
		nickName: "Canada"
	}
]

We can easily display this in React using map() function.

return (
    <div>
        {employee.map(emp =>
        <div>
            <h1>{emp.name}</h1>
            <p>Country: {emp.country}</p>
            <hr/>
        </div>
        )}
    </div>
)

When we run above example code, it will return an unique key because React wants to able to distinguish each item in an array of elements from other items. So here in below example, we have mapped elements to add a property called key to the element to be repeated.

The major changes made here are parentheses around the arrow function’s parameters and the new index parameter in the function, and the key property to the root element that returning inside the .map() function.

const displayEmployee = employee.map((emp, index) =>
	<div key={emp.name + index}>
		<h1>{emp.name}</h1>
		<p>Country: {emp.country}</p>           
		<hr/>
	</div>
	
}

Here’s the complete React component:

function App() {
    const employee = [
		{
			name: "Smith",
			country: "France"		
		},
		{
			name: "Danial",
			country: "Germany"
		},
		{
			name: "William",
			nickName: "Australia"
		},
		{
			name: "Andy",
			nickName: "Canada"
		}
	]
    
    const displayEmployee = employee.map((emp, index) =>
        <div key={emp.name + index}>
            <h1>{emp.name}</h1>
            <p>Country: {emp.country}</p>           
            <hr/>
        </div>
        
    }
  
    return (
        <div>
            {displayEmployee}
        </div>
    )
}

Conclusion

So if you’re just using plain JavaScript to create element then this is the easiest and fast solution to create elements in loop through array without using for loop. If you have any queries regarding this tutorial, then please feel free to let me know in the comments section below.

You may also like: