회사에서 AgGrid와 CustomFooter 컴포넌트를 이용하여 Pagination 기능을 구현하고 있던 와중에 기능은 문제없이 잘 동작하는데, 개발자도구(F12)에 다음과 같은 Warning 메시지가 출력되는 것을 확인하였다.
기능 구현에는 문제가 전혀 없었지만 개발자에게 빨간 경고문은 절대로 넘길 수 없는 직업병 같은 것이 있기 때문에 해당 경고를 잡고자 한다.
경고문 내용은 다음과 같다.
Waring: validateDOMNesting(...): <tr> cannot appear as a child of <table>. Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser.
이 경고는 React에서 유효한 HTML 구조를 유지하기 위한 경고 메시지이다.
HTML 테이블을 생성할 때, <tr> 요소는 <tbody>, <thead>,
또는 <tfoot> 요소 내에 있어야 한다는 뜻이다.
// 수정 전, 코드
return (
<>
<Table
className="ldCustomFooter"
style={{ width: '100%', display: 'inline-block' }}
>
<TableRow style={{ width: '100%', display: 'inline-block' }}>
<TableCell
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: '8px',
paddingBottom: '8px',
borderBottom: 'none',
}}
>
<div className={`${classes.footerDesc} ldCustomFooter`}>
// Someting
</div>
</TableCell>
</TableRow>
</Table>
</>
);
코드를 보면 TableRow 컴포넌트가 TableBody가 아니라 바로 Table 태그 안에 들어가 있는 모습을 볼 수 있다.
콘솔창의 경고문을 보면 tr태그(TableRow)는 TableBody 태그에 바로 들어가는 안된다고 나와있다.
∵ React에서 유효한 HTML 구조를 유지하기 위해서
따라서 유효한 HTML 및 DOM을 생성하기 위해서는 TableRow 태그를 TableBody 태그 안에 넣어줘야 한다.
// 수정 후, 코드
return (
<>
<Table
className="ldCustomFooter"
style={{ width: '100%', display: 'inline-block' }}
>
<TableBody style={{ width: '100%', display: 'inline-block' }}>
<TableRow style={{ width: '100%', display: 'inline-block' }}>
<TableCell
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: '8px',
paddingBottom: '8px',
borderBottom: 'none',
}}
>
<div className={`${classes.footerDesc} ldCustomFooter`}>
// Someting
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
</>
);
다음과 같이 TableRow 태그를 TableBody 태그 안에 넣어주면 더 이상 콘솔창에 경고문이 출력되지 않는다.
- 최상위 루트 엘리먼트는 하나여야 한다. 보통 div 또는 Fragment 태그로 감싸서 사용한다.
- 엘리먼트들은 항상 닫는 태그를 가져야 한다. 예를 들어
<br>
대신<br />
와 같이 사용해야 한다.- 모든 엘리먼트들은 올바른 중첩 구조를 가져야 한다. 즉, 부모 엘리먼트와 자식 엘리먼트 사이에 올바른 계층 구조를 유지해야 한다.
- 특정 태그들은 반드시 특정 부모 엘리먼트 안에서 사용되어야 한다(이 게시물에 해당되는 문제). 예를 들어
<td>
는<tr>
안에서 사용되어야 한다.- 특정 태그들은 항상 특정 엘리먼트를 가져야 한다. 예를 들어
<ul>
은<li>
엘리먼트를 가져야 한다.
위의 규칙을 지키면서 HTML 구조를 작성해야 React에서 유효한 구조를 유지할 수 있다.