Estoy tratando de representar datos json en una tabla usando useState en reaccionar pero no aparece por alguna razón.
Este es el archivo de reacción:
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;Este es el archivo json:
[ { "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" } ]El problema radica aquí:
{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> ); })}Dado que solo está devolviendo JSX, puede reemplazar sus corchetes con paréntesis. Además, asegúrese de usar una identificación única para la clave de iteración, de lo contrario, está garantizado que encontrará errores furtivos. Tiene identificadores en sus datos, así que usemos eso:
{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> )}