Using React Fragments for the first time

  • Up until React 16 each component had to return a single element: – – With the release of React 16, you were able to return an array of elements that a component would render: – – This is OK; but it has two problems: – – Because returning arrays didn’t…
  • On a large application with a suite of components this can very quickly lead to a set of wrapping elements that can produce a big set of HTML soup.
  • The difference is that a component doesn’t end up adding any extra markup into the DOM: – – First, we import just like we import from : – – And then we use it just like any other React component: – – The key here is that the resulting DOM…
  • However, swapping out the string interpolation using ES2015 template strings for a React suddenly made the entire code easier to follow, and allowed me to use an HTML entity: – – This is now easier to follow and allows me to use HTML entities and have them work as expected….
  • Not only do they clear up a lot of component code, but the fact that they have no output into the DOM should lead to fewer superfluous and elements that a lot of React applications are littered with.

React v16 was a very exciting release for React, and included many new features. In the recent React 16.2 release, improved support for Fragments was announced, and it’s this feature that I want to talk about today.

React v16 was a very exciting release for React, and included many new features. In the recent React 16.2 release, improved support for Fragments was announced, and it’s this feature that I want to talk about today.

Up until React 16 each component had to return a single element:

With the release of React 16, you were able to return an array of elements that a component would render:

This is OK; but it has two problems:

Because returning arrays didn’t feel that natural in React 16, it was far more common to eschew them in favour of wrapping elements in one containing element; most normally a or a .

On a large application with a suite of components this can very quickly lead to a set of wrapping elements that can produce a big set of HTML soup. Fragments solve this problem.

The element is imported from the module, and can be used just like any other JSX element. The difference is that a component doesn’t end up adding any extra markup into the DOM:

First, we import just like we import from :

And then we use it just like any other React component:

The key here is that the resulting DOM from…

Using React Fragments for the first time