HTML is the backbone of the web and the code you write should be semantic.
If you write semantic HTML, It's easier to read and ascertain developer intent. Take a look at the following semantic and unsemantic examples:
No thank you 👎
Yes please! 👍
It's also more accessible. Screenreaders read through elements and feed back the structure of the page to the person using the device. It's more useful to hear that there is a
header with a
navigation element, than a
div containing a bunch of
< React 16.2
Prior to React version 16, each component could only display a single element (that could contain other elements).
You can't do this 👎
You have to wrap the headings in a containing element 👍
Because of the necessary containing element, I've peeped a lot of code in the last year that when rendered looks like this:
Because the components that rendered the above HTML are built in isolation, it's very easy for us to just wrap our elements in a
div and forget about it. We often ignore the generated HTML in favour of the cute component display we get with React Developer Tools.
Hard to read and not very accessible.
One of the features that React 16 gave us was the ability to render an array of components without a containing element.
Hooray, no containing element!
But... it doesn't feel like HTML, and I don't want to have to put all my elements in an array just to get them to render!
Fragment is a new component you can import from React, which will replace all those horrible
When the page renders, all you'll see in the DOM is
<h1>Cool title</h1> <p>Cooler subtitle</p>
Look, no messy
You can reduce the code even more by using
<> which is equivalent to using
It works, but it looks a little weird to me, as if I accidentally put extra angle brackets in my code. I'll likely stick to
There are a couple of caveats with the
<></> syntax at present.
- If you want to give the fragment a key, you have to use
<Fragment />, not
<></>does not currently work in create-react-app
- You need to use Babel 7 and up to have this transpiled correctly, but you don't need to import
Fragmentinto the app context.
Write better HTML
I'm hoping that
<Fragment /> leads to us writing more semantic HTML, benefiting both developers and folks with accessibility needs.
Upgrade to React 16.2 and have a play!