2

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>;
    })
  )
}
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
dave_bell
  • 121
  • 9
  • 2
    Remove the curly brace characters at `stu=>{` & `})))` – Mee Mar 28 '23 at 01:35
  • If you add `{` in your function, you have to add the `return` keyword. e.g 1: `() => { /* you should add return key word*/}` e.g 2: `() => // no need of return key word` – Danielprabhakaran N Mar 28 '23 at 02:35

3 Answers3

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 by 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>
          )
      )
}
Arman Charan
  • 5,669
  • 2
  • 22
  • 32
2

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>
  ))
)
}
Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
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.

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38