React id property not found
I was doing copy coding for learn how to codes. but error keep happens. and error said my id property is undefined. How Can I solve this?? I tried change array’s name, array?.value things. I send my codes and error pages.
import React, {useState} from 'react';
import MidStudentCard from './MidStudentCard';
import './MidStudentList.css';
const studentData = [
{ id: 1, name: 'Sam', department:'ComputerSoftware', desc: 'This guy coding very well' },
{ id: 2, name: 'John', department: 'DronePicture', desc: 'He is expert about taking picture to drones' }
];
const MidStudentList = () => {
const [selectedStudent, setSelectedStudent] = useState(studentData);
const showDetails = (student) => {
setSelectedStudent(student);
};
return (
<div className="student-list-container">
<h1 className="title">Title</h1>
<div className="student-details">
<h2>Student Information</h2>
<p>Id: {studentData.id}</p>
<p>Name: {studentData.name}</p>
<p>Department: {studentData.department}</p>
<p>Description {studentData.desc}</p>
</div>
<div className="student-list">
<MidStudentCard
key={studentData.id}
value={studentData}
showDetails={showDetails}
/>
</div>
</div>
);
};
export default MidStudentList;
import React from 'react';
const MidStudentCard = ({student,showDetails}) => {
console.log(student);
return (
<div className="student-card" key={student.id}>
<p><strong>ID:</strong> {student.id}</p>
<p><strong>Name:</strong> {student.name}</p>
<p><strong>Department:</strong> {student.department}</p>
<button className="view-button" onClick={() => showDetails(student)}>View</button>
</div>
);
};
export default MidStudentCard;
2
Answers
You are getting an
undefined
becausestudentData
is an array, and not a single object.const MidStudentList = () => {
const [selectedStudent, setSelectedStudent] = useState(null); // Sửa thành null để lưu trữ sinh viên đã chọn
const showDetails = (student) => {
setSelectedStudent(student); // Lưu trữ sinh viên được chọn khi người dùng bấm
};
you need to add 2 lines i noted