I'm trying to render json data in a table using useState in react but it's not appearing for some reason.
This is the react file:
import React, { useState } from 'react'
import "../styling/Classes.css"
import data from "./mock-data.json";
function Classes() {
const [inputFields, setInputFields] = useState([
{ classCode: '', studentAmount: '' }
])
const [students, setStudents] = useState(data)
return (
<div className="classes-container">
<div className="classes-wrapper">
<h2>Classes</h2>
<table>
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Class code</th>
<th>Birth date</th>
<th>Mobile number</th>
</tr>
</thead>
<tbody>
{students.map((student) => {
<tr>
<td>{student.FirstName}</td>
<td>{student.LastName}</td>
<td>{student.ClassCode}</td>
<td>{student.BirthDate}</td>
<td>{student.MobileNumber}</td>
</tr>
})}
</tbody>
</table>
</div>
</div>
)
}
export default Classes;
This is the json file:
[
{
"id": 0,
"FirstName": "Saif",
"LastName": "Khadraoui",
"ClassCode": "13-MA1",
"BirthDate": "17/12/2003",
"MobileNumber": "78464329843"
},
{
"id": 1,
"FirstName": "test1",
"LastName": "Khadraoui",
"ClassCode": "13-MA1",
"BirthDate": "17/12/2003",
"MobileNumber": "83427912"
},
{
"id": 2,
"FirstName": "test2",
"LastName": "Khadraoui",
"ClassCode": "13-MA1",
"BirthDate": "17/12/2003",
"MobileNumber": "316283216821"
}
]
CodePudding user response:
The problem lies here:
{students.map((student) => {
// You are not returning the part that should render
<tr>
<td>{student.FirstName}</td>
<td>{student.LastName}</td>
<td>{student.ClassCode}</td>
<td>{student.BirthDate}</td>
<td>{student.MobileNumber}</td>
</tr>
})}
{students.map((student) => {
// Just return this part and it should render.
// Also don't forget to add a key for each tr
return (
<tr key={`${student.FirstName}-${student.LastName}`} >
<td>{student.FirstName}</td>
<td>{student.LastName}</td>
<td>{student.ClassCode}</td>
<td>{student.BirthDate}</td>
<td>{student.MobileNumber}</td>
</tr>
);
})}
CodePudding user response:
Since you are returning JSX only you can replace your curly brackets with parenthesis. Also, make sure to use a unique id for the iteration key, otherwise you are guaranteed to encounter sneaky bugs. You have ids in your data so let's use that:
{students.map(student => (
<tr key={student.id}>
<td>{student.FirstName}</td>
<td>{student.LastName}</td>
<td>{student.ClassCode}</td>
<td>{student.BirthDate}</td>
<td>{student.MobileNumber}</td>
</tr>
)}