0

I have a list of elements (Knowledgebase) which I wasnt to render onlyt in the case where one of the roles in the list "roles" is equel to zero. However, it is not renderting anything

In the web-console I can also see the log

react_devtools_backend.js:4061 Warning: validateDOMNesting(...): <tr> cannot appear as a child of <td>.
    at tr
    at td
    at tr
    at tbody
    at table
    at UserList (http://localhost:3000/static/js/bundle.js:3997:91)
    at Route (http://localhost:3000/static/js/bundle.js:46456:29)
    at Switch (http://localhost:3000/static/js/bundle.js:46658:29)
    at Router (http://localhost:3000/static/js/bundle.js:46091:30)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:45712:35)
    at App

Code:

<td>
  {user.roles.map((role) => {
    if (role === "0") {
      user.knowledgeBase.map((techField) => (
        <tr key={techField}>
          <td>{techField}</td>
        </tr>
      ));
    }
  })}
</td>
jolo
  • 605
  • 1
  • 5
  • 12

3 Answers3

0

You are rendering a Table Row <tr>, inside a Table data cell <td>. this is semantically not correct. More info here and here. Instead, you can render a new <table> inside your outer <td>.

<td>
     <table>
         {user.roles.map((role) => {
            if (role === "0") {
              user.knowledgeBase.map((techField) => (
                <tr key={techField}>
                  <td>{techField}</td>
                </tr>
              ));
            }
          })}
     </table>
</td>
jolo
  • 605
  • 1
  • 5
  • 12
0

Actually, the problem is that you just forgot to return items that you want to render on the first map call.

<td>
{user.roles.map((role) => {
  if (role === "0") {
    return user.knowledgeBase.map((techField) => (
      <tr key={techField}>
        <td>{techField}</td>
      </tr>
    ));
  } else return "";
})} 
</td> 

Also, you can use shorter way to implement this:

<td>
{user.roles.map(
  (role) =>
    role === "0" &&
    user.knowledgeBase.map((techField) => (
      <tr key={techField}>
        <td>{techField}</td>
      </tr>
    ))
)}
</td> 
ouflak
  • 2,458
  • 10
  • 44
  • 49
hadi karami
  • 13
  • 1
  • 3
0

This will be more relevant in your problems domain

 {user.roles.includes(0) &&
    user.knowledgeBase.map((techField) => (
        <tr key={techField}>
         <td>{techField}</td>
       </tr>
  ))}
Harsh Mangalam
  • 1,116
  • 1
  • 10
  • 19