React Has Been Teaching You Invalid HTML!
HTML5 has a class of elements called void elements. These include:
area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr
You can self-close these elements (e.g.
<hr />), meaning - no additional closing tag is necessary (and adding one is generally considered improper). But what about all the other elements? Can you self-close a
div can be sized and given a background image in CSS for example.
Nevertheless this is not valid HTML and the consequences can be pretty dire! HTML parsers (such as your browser) are trying to be extra helpful in this case and interpret the tag as un-closed and nesting everything below it as children of the tag. So you write this:
<!-- ... --> <div class="placeholder" /> <input type="text" /> <!-- ... -->
And the browser interprets it like this:
<!-- ... --> <div class="placeholder"> <input type="text" /> </div> <!-- ... -->
In fact, the W3C’s official HTML validator will show 3 errors if you try to do that:
By now, if you’ve done this you probably feel bad… but it’s not your fault. Front End frameworks (like React) have been spoiling us for years, fixing our HTML for us and, in the process, teaching us how to write some terribly invalid HTML.
That’s not all, our beloved linter, ESLint, particularly the ESLint-plugin-React, has been auto-“correcting” our code too: