EN
React - validateDOMNesting table warning
1
answers
0
points
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
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