Home > Mobile >  Not able to access Variable inside JSX
Not able to access Variable inside JSX

Time:04-26

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>
  );
}`

CodePudding user response:

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}
  />}
  • Related