Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to access Variable inside JSX

I am trying to use the variable StudentId inside JSX of the same component but I’m getting the error as "TypeError: Cannot read properties of undefined (reading ‘name’)"
What am I doing wrong here? PS I’m new to react. Also,I’m getting the value of StudentId in console. Thank You in advance.

`

export default function StudentDetail() {
  const router = useRouter();
  const StudentId = router.query.StudentID;
  console.log(StudentId);
  const data = [
    {
      name: "Abc",
      contact: "9909990990",
      
    },
    {
      name: "Def",
      contact: "8880808008",
    },
    {
      name: "ghi",
      contact: "7700700077",
    },
  ];

  return (
    <div>
      <TableList
        name={data[StudentId].name}
        contact={data[StudentId].contact}
      />
    </div>
  );
}`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This happens during initial rendering, provide some validation. I assume StudentId is array index like 0, 1 etc.

  {StudentId >= 0 && <TableList
    name={data[StudentId].name}
    contact={data[StudentId].contact}
  />}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading