React DOM elements should be nested properly

  • REACT_INVALID_DOM_NESTING
  • Code Quality
  • Low
  • react

This rule applies when React DOM elements are not nested properly according to the HTML specification.

React requires using valid DOM elements and generates warnings for invalid DOM trees even though browsers may apply recoveries. The warnings are necessary because invalid trees may confuse React and break re-renderings in the future versions of React.

For example, React outputs warnings in the following cases:

  1. A <tr> is used inside <table> without the <tbody>. In this case, browsers insert the <tbody> in the generated DOM tree. Although the HTML specification says <tbody> is not required in some cases, it is recommended to always match the generated DOM tree.
  2. An extraneous space is used in JSX code where a text node is not allowed. In JSX, most extraneous spaces are automatically removed. However, if you put a space in the same line as the previous tag like <tr> <td>, it is not removed and causes a React warning.
  3. A non-phrasing content is used inside <p>. The <p> element allows only phrasing content like <span> or <code>. If you use a non-phrasing element like <pre> or <div>, a React warning occurs.

Noncompliant Code Example

View with compliant examples side by side
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(
  <>
    <table>
      {/* REACT_INVALID_DOM_NESTING alarm because '<tbody>' is missing. */}
      <tr><td>Example 1</td></tr>
    </table>

    <table>
      <tbody>
        {/* REACT_INVALID_DOM_NESTING alarm because there are extraneous spaces after '<tr>'. */}
        <tr>  <td>Example 2</td></tr>
      </tbody>
    </table>

    <p>
      {/* REACT_INVALID_DOM_NESTING alarm because '<pre>' is not a phrasing content. */}
      <pre>Example 3</pre>
    </p>
  </>
);

Compliant Code Example

View with noncompliant examples side by side
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(
  <>
    <table>
      <tbody>
        <tr><td>Example 1</td></tr>
      </tbody>
    </table>

    <table>
      <tbody>
        <tr><td>Example 2</td></tr>
      </tbody>
    </table>

    <p>
      <code>Example 3</code>
    </p>
  </>
);

Version

This rule was introduced in DeepScan 1.38.0.

See

  • <tr>: The Table Row Element

  • Content Categories

  • React Warning: In HTML, <tr> cannot be a child of <table>. Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser. This will cause a hydration error.

  • React Warning: In HTML, whitespace text nodes cannot be a child of <tr>. Make sure you don't have any extra whitespace between tags on each line of your source code. This will cause a hydration error.

  • React Warning: In HTML, <pre> cannot be a descendant of <p>. This will cause a hydration error.

Was this documentation helpful?