Nested Looping in React
Array Structure
You’re using an array of colleges.
Each college has its own array of students.
function App() {
const collegeData = [
{
name: "IET Alwer",
city: "Alwer",
website: "https://www.iet.ac.in/",
student: [
{
name: "Anil sidhu",
age: 29,
email: "anil@test.com",
},
{
name: "Beter",
age: 20,
email: "peter@test.com",
},
{
name: "Bruce",
age: 25,
email: "bruce@test.com",
},
],
},
{
name: "IIT Delhi",
city: "Delhi",
website: "https://www.iit.ac.in/",
student: [
{
name: "Anil sidhu",
age: 29,
email: "anil@test.com",
},
{
name: "Beter",
age: 20,
email: "peter@test.com",
},
{
name: "Bruce",
age: 25,
email: "bruce@test.com",
},
],
},
{
name: "KCIET Hisar",
city: "Hisar",
website: "https://www.kciet.ac.in/",
student: [
{
name: "Anil sidhu",
age: 29,
email: "anil@test.com",
},
{
name: "Beter",
age: 20,
email: "peter@test.com",
},
{
name: "Bruce",
age: 25,
email: "bruce@test.com",
},
],
},
];
Outer Loop: Loop through colleges
return (
<div>
<h1>Reuse component in Loop</h1>
{collegeData.map((college, index) => (
<div key={index}>
<College college={college} />
</div>
))}
</div>
);
}
Here:
- You loop over the
collegeData
. - Pass each college object to
College
component. - Use
key={index}
for unique identification.
Outer Component: College.jsx
This component shows the college details and sends the student data to the inner loop.
import Student from "./Student";
function college({ college }) {
return (
<div
style={{
backgroundColor: "#ccc",
padding: "20px",
margin: "20px",
borderBottom: "2px solid #000",
borderRadius: "10px",
}}
>
<h1>Name:{college.name}</h1>
<ul>
<li>
<h3>City:{college.city}</h3>
</li>
<li>
<h3>Website:{college.website}</h3>
</li>
<li>
<Student student={college.student} />
</li>
</ul>
</div>
);
}
export default college;
Displays college data
Sends college.student
to the Student
component
Inner Loop: Student.jsx
This component loops through students for each college.
function Student({ student }) {
return (
<div>
<h3>Student</h3>
{student.map((student) => (
<div>
<ul>
<li>
<h4>{student.name}</h4>
</li>
</ul>
</div>
))}
</div>
);
}
export default Student;
Loops through the student
array
Shows the name of each student
Summary
App.jsx
→ Loops through colleges using.map()
College.jsx
→ Shows each college and sends students to the next componentStudent.jsx
→ Loops through and displays students