skip to Main Content

Strangely, I have <Avatar> that works with single object parse using .map

<Flex>
  <div></div>
  {studentsjson.map((thr) => (
    <Avatar color="red" key={thr.id} component={Link} to="/complete">
      {thr.Name}
    </Avatar>
  ))}
</Flex>

However, below does not work

{
  teacher.map((thr) =>
    thr.students.map((stu) => {
      <Avatar color="red" key={stu.id} component={Link} to="/complete">
        {stu.studentName}
      </Avatar>;
    })
  )
}

3

Answers


  1. Following place is where you are making mistake.

    {
    teacher.map((thr) =>
      thr.students.map((stu) => { // this map is not returning anything
        <Avatar color="red" key={stu.id} component={Link} to="/complete">
          {stu.studentName}
        </Avatar>;
      })
    )
    }
    

    add a return statement or remove { curly braces.

    {
    teacher.map((thr) =>
      thr.students.map((stu) => (
        <Avatar color="red" key={stu.id} component={Link} to="/complete">
          {stu.studentName}
        </Avatar>
      ))
    )
    }
    
    Login or Signup to reply.
  2. In the second block of code, the problem is that you are only looping through students creating <Avatar/>s but nothing is returned, you either have to use

    implicit return :

    teacher.map((thr) =>
      thr.students.map((stu) => (
        <Avatar color="red" key={stu.id} component={Link} to="/complete">
          {stu.studentName}
        </Avatar>
      ))
    )
    

    or explicit return :

    teacher.map((thr) =>
      thr.students.map((stu) => {
        return (
          <Avatar color="red" key={stu.id} component={Link} to="/complete">
            {stu.studentName}
          </Avatar>
        )
      })
    )
    

    to return an non empty array.

    Login or Signup to reply.
  3. As others have mentioned, the callback argument of the nested .map returns nothing. Hence, nothing can be expected to render. This can be fixed removing the curly braces to perform an "implicit return".

    I have a feeling you’ll want to use Array.prototype.flatMap as well; e.g.

    {
      teachers.flatMap(
          teacher =>
              teacher.students.map(
                   student =>
                       <Avatar color="red" key={stu.id} component={Link} to="/complete">
                         {stu.studentName}
                       </Avatar>
              )
          )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search