Skip to content

Rule proposal: prevent some DOM elements from having children or dangerouslySetInnerHTML #709

Closed
singapore/lint-condo
#240
@lencioni

Description

@lencioni
Collaborator

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

Activity

ljharb

ljharb commented on Jul 26, 2016

@ljharb
Member

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

lencioni commented on Jul 26, 2016

@lencioni
CollaboratorAuthor

Yeah, I think the 99% solution is great.

lencioni

lencioni commented on Jul 26, 2016

@lencioni
CollaboratorAuthor

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

ljharb

ljharb commented on Jul 26, 2016

@ljharb
Member

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

lencioni commented on Jul 26, 2016

@lencioni
CollaboratorAuthor

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

ljharb

ljharb commented on Jul 26, 2016

@ljharb
Member

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

lencioni commented on Jul 26, 2016

@lencioni
CollaboratorAuthor

That works for me!

self-assigned this
on Jan 29, 2017
added a commit that references this issue on Jan 29, 2017
67d62bd

9 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    Participants

    @ljharb@lencioni@kepi0809

    Issue actions

      Rule proposal: prevent some DOM elements from having children or dangerouslySetInnerHTML · Issue #709 · jsx-eslint/eslint-plugin-react