I am trying to make a project with React that can display course homework on a to-do list. I currently have some test data, shown here:
const courses = [
{
courseName: "Fundies 2",
classCode: "CS2510",
startTime: "4:35 PM",
location: "236 Richards Hall",
color: "red",
homework: [{ hwName: "HW3", timeDue: "8:30 PM" }]
},
{
courseName: "Mathematical Reasoning",
classCode: "MATH1365",
startTime: "10:20 AM",
location: "235 Ryder Hall",
color: "blue",
homework: [
{ hwName: "HW2", timeDue: "midnight" },
{ hwName: "HW3", timeDue: "midnight" },
]
},
];
I made a function to create a component out of this data, shown below.
const formattedCourses = courses.map((course) => {
return (
<Task
key={course.homework[1].hwName}
timeDue={course.homework[1].timeDue}
courseName={course.courseName}
hwName={course.homework[1].hwName}
color={course.color}
/>
);
});
I want the component to be made with the first entry in the homework array. However, whenever I try to compile, I get
"TypeError: Cannot read properties of undefined (reading 'hwName')"
How can I fix this?
Any and all help is greatly appreciated!
CodePudding user response:
You index is incorrect. If you want the first entry then it should be 0 instead of 1
const formattedCourses = courses.map((course) => {
return (
<Task
key={course.homework[0].hwName}
timeDue={course.homework[0].timeDue}
courseName={course.courseName}
hwName={course.homework[0].hwName}
color={course.color}
/>
);
});