<thead> cannot appear as a child of <div>. when using react material-ui/core

Viewed 2532

first time react user (BE learning FE here)

when i try to create my table I am getting these errors, and as a result my table wont populate with the data I am trying to pull in via my API.

the error messages I am getting in the console:

Warning: validateDOMNesting(...): <thead> cannot appear as a child of <div>. Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>.

my code:

        <Paper>
            <Grid container>
                <Grid item xs={6}>
                    <DCandidateForm />
                </Grid>

                <Grid item xs={6}>
                    <TableContainer>
                        <TableHead>
                            <TableRow>
                                <TableCell>Name</TableCell>
                                <TableCell>Mobile</TableCell>
                                <TableCell>Blood Group</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {
                                props.dCandidateList.map((record, index) => {
                                    return (<TableRow key={index}>
                                        <TableCell>{record.fullName}</TableCell>
                                        <TableCell>{record.mobile}</TableCell>
                                        <TableCell>{record.bloodGroup}</TableCell>
                                    </TableRow>)
                                })
                            }
                        </TableBody>
                    </TableContainer>
                </Grid>
            </Grid>
        </Paper>


note: I am using the @material-ui/core package for react. 
Is it a problem with how i am structuring my table?


1 Answers

You need to wrap it with a Table, not just a TableContainer. Example from the docs. The container is just for styling purposes. You still need the Table to create the underlying table element.

<TableContainer>
  <Table>
    <TableHead>
      <TableRow>
        <TableCell>Name</TableCell>
        <TableCell>Mobile</TableCell>
        <TableCell>Blood Group</TableCell>
      </TableRow>
    </TableHead>

    ...

  </Table>
</TableContainer>

Without the component prop passed to it, TableContainer defaults to a div as the wrapping element. This is what's causing your error. The final HTML will end up being:

<div>
  <thead>
  ...
  </thead>
  <tbody>
  ...
  </tbody>
</div>

Which isn't correct syntax for a table.

If you don't need to wrap the table with a different tag (like Paper in the example), you could remove the container altogether.

Related