Eslint-plugin-react: Rule proposal: prevent some DOM elements from having children or dangerouslySetInnerHTML

Created on 26 Jul 2016  路  11Comments  路  Source: yannickcr/eslint-plugin-react

There are some HTML elements that are normally self-closing (e.g. img, br, hr). If you try to give these children, React will give you a warning like

Invariant Violation: img is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

It would be nice to have a rule enforcing this.

Bad:

<img src="path/to/img.jpg">
  Children
</img>
<img src="path/to/img.jpg" dangerouslySetInnerHTML={{ __html: 'HTML' }} />
<img src="path/to/img.jpg" children="Children" />

Good:

<img src="path/to/img.jpg" />

The full list that React uses can be found:

Which comes out as:

  • area
  • base
  • br
  • col
  • embed
  • hr
  • img
  • input
  • keygen
  • link
  • menuitem
  • meta
  • param
  • source
  • track
  • wbr
accepted help wanted new rule

All 11 comments

This seems like an excellent idea, and one that's mostly enforceable with both jsx and React.createElement (it wouldn't be enforceable with spreaded props that contain a "children" key, but I think that's OK)

Yeah, I think the 99% solution is great.

What should this be called? void-element-tag-no-children?

Since it's just for DOM elements, what about self-closing-dom-elements-no-children? "void element" isn't a term I'm familiar with, but "self-closing" is.

I thought about that, but I think self-closing may refer to elements that are also able to accept children but happen to be rendered without children, such as div. I'm not totally sold on the void naming either, but it is the language used by React and the HTML spec: https://www.w3.org/TR/html-markup/syntax.html#syntax-elements

In that case, maybe void-dom-elements-no-children? "tag" isn't appropriate if it's not just jsx, and i like including "dom" to point out that it's not for custom components.

That works for me!

why is wbr on this list??

@kepi0809 because <wbr /> is a self-closing element?

@kepi0809 because <wbr /> is a self-closing element?

@ljharb https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr it's not?

@kepi0809 HTML5 permits self-closing elements to omit the closing slash; anything is a self-closing element if it can not contain children. See "Tag omission" on that page.

Was this page helpful?
0 / 5 - 0 ratings