void-dom-elements-no-children

Try in Playground
react-best-practicesBest PracticeWarning

0

No tags

No CWE or CVE

This rule will notify you when you have passed children to a self-closing HTML element.

These elements are known as void DOM elements.

View a similar rule from ESLint, react/void-dom-elements-no-children

Ast Rule: html element


void-dom-elements-no-children

How to write a rule
const CHILDREN_PROPS = [
  "children",
  "dangerouslySetInnerHTML"
]

const VOID_DOM_ELEMENTS = {
  area: true,
  base: true,
  br: true,
  col: true,
  embed: true,
  hr: true,
  img: true,
  input: true,
  keygen: true,
  link: true,
  menuitem: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true,
};


function isVoidDOMElement(elementName) {
  return !!VOID_DOM_ELEMENTS[elementName];
}

const VOID_ELEMENTS = ["br", "hr", "img"]

function visit(node, filename, code) {
  if (!node || !node.tag) return;

  // if this isn't a void element skip it
  if (!isVoidDOMElement(node.tag?.value)) return;

  // does this void element have children
  const hasChildren = node.htmlChildren.length !== 0;

  // does this void element have children passed as a prop
  const hasChildrenProp = node.attributes.some(child => CHILDREN_PROPS.includes(child.name?.value));

  // if there are children of any type, show an error
  if (hasChildren || hasChildrenProp) {
    const error = buildError(
      node.tag.start.line,
      node.tag.start.col,
      node.tag.end.line,
      node.tag.end.col,
      `Disallow void DOM elements (e.g. "<img />", "<br />") from receiving children`,
      "WARNING",
      "BEST_PRACTICE"
    )
    addError(error)
  }
}

incorrect-void-element-usage.jsx

Expected test result: has error

Void elements with children

<img>Some text</img>
<br>Children</br>
<br children='Children' />
<br dangerouslySetInnerHTML={{ __html: 'HTML' }} />

correct-void-element-usage.jsx

Expected test result: no error

Void elements without children

<img />
<div>Children</div>
<div children='Children' />
<div dangerouslySetInnerHTML={{ __html: 'HTML' }} />
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.