Languages

React - validateDOMNesting table warning

0 points
Asked by:
Dirask Community
6900

When I was creating a simple table in React I got the warning. Do you know how to get rid of it?

Warning message:

index.js:1 Warning: validateDOMNesting(...): <th> cannot appear as a child of <table>.
    at th
    at table
    at div
    at App

My code:

import React from 'react';

const TableColumns = () => {
  return (
    <>
      <td style={{ border: '1px solid black' }}>cell 1</td>
      <td style={{ border: '1px solid black' }}>cell 2</td>
    </>
  );
};

const App = () => {
  return (
    <div>
      <table style={{ border: '1px solid black' }}>
        <th>My Table</th>
        <tr>
          <TableColumns />
        </tr>
      </table>
    </div>
  );
};

export default App;

 

1 answer
0 points
Answered by:
Dirask Community
6900

I found the solution:

The th element should be nested under a tr and thead. Also, the table body should be wrapped with <tbody>.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const TableColumns = () => {
  return (
    <>
      <td style={{ border: '1px solid black' }}>cell 1</td>
      <td style={{ border: '1px solid black' }}>cell 2</td>
    </>
  );
};

const Table = () => {
  return (
    <div>
      <table style={{ border: '1px solid black' }}>
        <thead>
          <tr>
            <th>My Table</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <TableColumns />
          </tr>
        </tbody>
      </table>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<Table/>, root );
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join