Void elements should neither have children nor dangerouslySetInnerHTML prop

  • REACT_VOID_ELEMENT_WITH_CHILDREN
  • Error
  • High
  • react

This rule applies when void elements have either children or dangerouslySetInnerHTML prop.

HTML elements such as <area />, <br />, and <input /> are void elements which are only self-closing without any content.

Therefore, React will throw an exception if you set either children or dangerouslySetInnerHTML prop for a void element.

Noncompliant Code Example

import React from 'react';
import ReactDOM from 'react-dom';

// Example 1
class Hello extends React.Component {
    render() {
        return <hr>Hello</hr>; // REACT_VOID_ELEMENT_WITH_CHILDREN alarm because '<hr>' is a void element.
    }
}
var container = document.createElement('app');
ReactDOM.render(<Hello />, container);

// Example 2
ReactDOM.render(
    <input dangerouslySetInnerHTML={{ __html: "myHTML" }} />, // REACT_VOID_ELEMENT_WITH_CHILDREN alarm because '<input>' is a void element.
    document.getElementById("root")
);

// Example 3
var elem = React.createElement("br", null, 'Children'); // REACT_VOID_ELEMENT_WITH_CHILDREN alarm because '<br>' is a void element.
ReactDOM.render(elem, document.getElementById("app"));

// Example 4
var elem = React.createElement("img", { children: 'Children' }); // REACT_VOID_ELEMENT_WITH_CHILDREN alarm because '<img>' is a void element.
ReactDOM.render(elem, document.getElementById("app"));

Compliant Code Example

import React from 'react';
import ReactDOM from 'react-dom';

// Example 1
class Hello extends React.Component {
    render() {
        return <hr />;
    }
}
var container = document.createElement('app');
ReactDOM.render(<Hello />, container);

// Example 2
ReactDOM.render(
    <input />,
    document.getElementById("root")
);

// Example 3
var elem = React.createElement("div", null, 'Children');
ReactDOM.render(elem, document.getElementById("app"));

// Example 4
var elem = React.createElement("div", { children: 'Children' });
ReactDOM.render(elem, document.getElementById("app"));

Version

This rule was introduced in DeepScan 1.5.0-beta.

See

  • React Error: hr is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

  • React Error: input is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

  • React Error: br is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

  • React Error: img is a void element tag and must neither have children nor use dangerouslySetInnerHTML.