【初心者向け】Reactで発生する「REACT ERROR cannot appear as a child of . See (unknown) > thead > th」エラー: 原因と解決策
"REACT ERROR <th> cannot appear as a child of <thead>. See (unknown) > thead > th" の原因と解決策
原因
HTMLの仕様では、<thead>要素内に直接<th>要素を配置することはできません。<th>要素は<tr>要素の子要素として配置する必要があります。**
解決策
以下の方法で解決できます。
- <tr>要素内に<th>要素を配置する
<table>
<thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>田中 太郎</td>
<td>30</td>
</tr>
<tr>
<td>2</td>
<td>佐藤 花子</td>
<td>25</td>
</tr>
</tbody>
</table>
- <tbody>要素を追加する
<table>
<thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</tr>
</thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</tr>
</table>
補足
- <thead>要素は、表の見出し行を定義するために使用されます。
<table>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</table>
修正コード
<table>
<thead>
<tr>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>田中 太郎</td>
<td>30</td>
</tr>
<tr>
<td>2</td>
<td>佐藤 花子</td>
<td>25</td>
</tr>
</tbody>
</table>
説明
問題のあるコードでは、<thead>要素内に<th>要素が直接配置されています。修正コードでは、<tr>要素内に<th>要素を配置し、<tbody>要素を追加しています。これにより、HTMLの仕様に準拠した正しいコードになります。**
オプション
<table>
<tr>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</tr>
</table>
オプションのコードでは、<tbody>要素を省略しています。この場合、Reactは自動的に<tbody>要素を追加します。
他の方法
これは最も一般的な方法で、上記の回答ですでに説明されています。
React.Fragment コンポーネントを使用して、<th>要素をグループ化することができます。
<table>
<thead>
<React.Fragment>
<th>ID</th>
<th>名前</th>
<th>年齢</th>
</React.Fragment>
</thead>
<tbody>
<tr>
<td>1</td>
<td>田中 太郎</td>
<td>30</td>
</tr>
<tr>
<td>2</td>
<td>佐藤 花子</td>
<td>25</td>
</tr>
</tbody>
</table>
createElement 関数を使用して、<th>要素を含む仮想 DOM を作成することができます。
import React from 'react';
const MyTable = () => {
const header = React.createElement('thead', null, [
React.createElement('th', null, 'ID'),
React.createElement('th', null, '名前'),
React.createElement('th', null, '年齢'),
]);
const body = React.createElement('tbody', null, [
React.createElement('tr', null, [
React.createElement('td', null, '1'),
React.createElement('td', null, '田中 太郎'),
React.createElement('td', null, '30'),
]),
React.createElement('tr', null, [
React.createElement('td', null, '2'),
React.createElement('td', null, '佐藤 花子'),
React.createElement('td', null, '25'),
]),
]);
return React.createElement('table', null, [header, body]);
};
export default MyTable;
それぞれの方法の利点と欠点
方法 | 利点 | 欠点 |
---|---|---|
tbody 要素 | シンプルで分かりやすい | 冗長なコードになる可能性がある |
React.Fragment | コードをより論理的にグループ化できる | 構文が少し複雑になる |
createElement 関数 | 柔軟性が高い | 複雑で分かりにくいコードになる可能性がある |
javascript jquery ruby-on-rails