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.

In recent years, we've fallen in love with React.js. React methodology involves writing self contained components that look like HTML but is actually JSX (to over-simplify, it's writing HTML tags in JavaScript).

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

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

  1. If you want to give the fragment a key, you have to use <Fragment />, not <></>
  2. <></> does not currently work in create-react-app
  3. You need to use Babel 7 and up to have this transpiled correctly, but you don't need to import Fragment into 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!

Thanks to Karthik and Neil for their help!