Cleaner Markup with React 16
One of the new features in React 16 is that it allows you to return an array of components to render.
What is this useful for? Mostly for rendering cleaner markup. This will lead to a nicer looking DOM (for anyone looking), as well as slightly lighter payloads for SSR. It may also be useful in certain scenarios where the exact structure of the DOM is important.
Recently I’ve been working on creating accessible forms code. I’m aiming to make the components maximally composable, and aiming to keep the code as DRY as possible.
In trying to do this I’ve started using higher order components for adding errors, labels, and legends to the various form components. It ends up looking like this when writing a particular input that needs a label and inline error.
The withLabel
component looks like:
It associates the label with the base component using the id prop and htmlFor
.
The error component looks like:
It associates the inline error with the base component by giving the base component an aria-describedby
prop referring to the errors' id.
It also adds an aria-invalid
prop if an error is present.
The markup rendered by the Text
component with a label and error ends up looking like:
Not very pretty. We’ve got a bunch of extra divs, and we have a bunch of nesting we don’t need.
In React 16 we can make our withLabel
and withError
components return arrays or fragments.
We will use the new JSX fragment syntax .
Our HOC will now look like:
After changing over withError the rendered markup will look like:
No wrapping divs, just exactly what we wanted rendered.
You can find the source for this at DylanVann/react-cleaner-markup-example.