Akusas
Akusas

Reputation: 529

validateDOMNesting(...): <td> cannot appear as a child of <a>

I'm creating a table in a React project using Material UI, but I get this error. I'm trying to have the whole row be a link to a page that contains more information on the subject. This is the Table code snippet:

<TableBody>
  {data.map((item, index) => {
    return (
      <TableRow key={index} className={classes.row} component={RouterLink} to={`/subject/${item.Name}`}>
        <TableCell scope="row">{item.Id}</TableCell>
        <TableCell scope="row">{item.Name}</TableCell>
        <TableCell scope="row">{item.Group}</TableCell>
      </TableRow>
    )
  })}
</TableBody>

I'm coding in Typescript if that has got anything to do with the problem. RouterLink is Link from react-router-dom, had to rename it as I refer to Link from Material UI further down in the Component.

Upvotes: 0

Views: 4188

Answers (3)

Sebastian
Sebastian

Reputation: 3594

Rather than reiterating what the error message says I would like you to reconsider your design. Moving the link into click handler is a big accessibility issue. In addition to that having a table row as a link is also quite unintuitive for user experience. Table context might be selected and copied. Moving away from the page when doing this common task is quite disruptive.

Have you considered adding an additional cell with a link icon that is properly labelled (aria-label) like suggested in https://stackoverflow.com/a/58093606/3406963?

Upvotes: 0

Mukesh Pant
Mukesh Pant

Reputation: 1

Seems you forgot to attach the error. anyway, the answer posted above by Mr. Crowder explains this in detail. Option i) put a click handler on tr and iii) wrap the tr within a could be implemented.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074545

I'm trying to have the whole row be a link...

You can't do that. a is not a valid child for table or tbody or tr, and (as the error says) td is not a valid child element for an a element.

There are other things you can do:

  • You can have a click handler on the tr and take action on click (but it can't be an actual a element).
  • You can use a elements around the content of each td.
  • (Fairly common) You can have a single td containing the link.

Upvotes: 3

Related Questions