React.Fragment and Semantic HTML

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 anchors.

< 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:

Too. Many. div's.

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.

React 16.2+

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!

Enter...drumroll<Fragment />!

Fragment is a new component you can import from React, which will replace all those horrible div's.

When the page renders, all you'll see in the DOM is

<h1>Cool title</h1>
<p>Cooler subtitle</p>

Look, no messy div's!

You can reduce the code even more by using <> which is equivalent to using <Fragment />

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 <Fragment />.

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 <></>