Closed
Description
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 usedangerouslySetInnerHTML
.
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:
- https://github.com/facebook/react/blob/85dcbf83/src/renderers/dom/shared/ReactDOMComponent.js#L421
- https://github.com/facebook/react/blob/85dcbf83/src/renderers/dom/shared/ReactDOMComponent.js#L449
Which comes out as:
area
base
br
col
embed
hr
img
input
keygen
link
menuitem
meta
param
source
track
wbr
Activity
ljharb commentedon Jul 26, 2016
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)lencioni commentedon Jul 26, 2016
Yeah, I think the 99% solution is great.
lencioni commentedon Jul 26, 2016
What should this be called?
void-element-tag-no-children
?ljharb commentedon Jul 26, 2016
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.lencioni commentedon Jul 26, 2016
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-elementsljharb commentedon Jul 26, 2016
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.lencioni commentedon Jul 26, 2016
That works for me!
Add void-dom-elements-no-children rule
9 remaining items