Menu

React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

React 16.2 brings fragments for cleaner markup

After what feels like a long period of stagnation for React.js, the open source team working on the popular library has accelerated pace after the release of the large scale rewrite in React 16. With 16.2 comes a new feature to React.js: Fragments

With only months after releasing version 16, the team is already unleashing the second minor version, React 16.2.0. The major attraction of this new version are fragments. Fragments allow developers to produce cleaner DOM structures by reducing unnecessary container elements.

Since the beginning the render function of React.js components have needed to output a single DOM element in the JSX format. This has lead to increased markup and wrapper elements, as that element (often a "div") has been required to contain any other elements:

render() {
  return (
    <div>
      <ComponentOne />
      <ComponentTwo />
    </div>
  );
}

With fragments arriving in 16.2.0 the library adds the capability to mark elements in React components, which will not be output in the generated HTML structure - either in the DOM structure of the browser, or static HTML in the output when using Server Side Rendering.

After React 16.2 developers can use either the Fragment component or a an empty shorthand:

render() {
  return (
    <>
      <ComponentOne />
      <ComponentTwo />
    </>
  );
}

In this method the output will only contain the output of ComponentOne and ComponentTwo, and the extraneous div from the first example is ignored. Learn more about React 16.2 and it's details from the React.js documentation on Fragments.

Written by Jorgé on Monday December 4, 2017

Permalink -

« Benchmarking HTTP/2 - SkateJS 5.0 released - React.js compatible Web Components abstraction »