Loop inside React JSX


This is an example of using Loop inside React JSX

Using Array map function is very common way to loop through an Array of elements and create components according them in React, this is a great way to do a loop which is pretty efficient and tidy way to do your loops in JSX, It's not the only way to do it, but the preferred way.

Let's assume we have a complex JSON data and in our component we want to display list items inside another items list.

data.json

{
"Skills": [
{
"Area": "Programming Language",
"SkillSet": [
{
"Name": "Java",
"Hot": true
},
{
"Name": "C#",
"Hot": false
},
{
"Name": "Python",
"Hot": false
}
]
},
{
"Area": "Web-Based Application Development",
"SkillSet": [
{
"Name": "JavaScript (ES5, ES6)",
"Hot": true
},
{
"Name": "TypeScript",
"Hot": false
},
{
"Name": "HTML5",
"Hot": true
},
{
"Name": "CSS (SCSS/SASS)",
"Hot": true
},
{
"Name": "React",
"Hot": true
}
]
}
]
}

Here is a complete example using map to loop div and li based on a JSON data structure.

SkillDetail.js

import React, { Component } from 'react';
import profile from "../Profile/data";

class SkillDetail extends Component {
render() {
return (
<div>
{
profile.Skills.map((skill) => {
return (
<div>
<h4>{skill.Area}</h4>
<ul>
{
skill.SkillSet.map((skillDetail) => {
return (
<li>
{skillDetail.Name}
</li>
);
})
}
</ul>
</div>
);
})
}
</div>

);
}
}
export default SkillDetail;
Most Helpful This Week