/ react

React v16.2 Fragments - Configuration

Level - Intermediate. Read Time ~ < 10 minutes.

TL;DR

Pull Request - React Fragments branch

So, React 16 brings us the hydrate method for DOM rendering and v16.2 comes with Fragments. This blog post is going to focus on Fragments. To learn more about Fragments refer to the official React documentation, rather than me paraphrasing Official Documentation.

To enable Fragments for my project, I had to install the below packages. You'll notice these are beta and this is what the state of affairs were in December 2017. So depending on when you stumble across this post, it may have surpassed beta release.

npm i --save-dev [email protected]^8.0.0-beta.0 @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected]

Webpack

As I was using the ever popular Webpack. For my client side Webpack configuration I had to add the below configuration to my JavaScript loaders. I opted to not use a .babelrc file as this conflicted with the configuration I had for my Jest tests.

module: {
      loaders: [
        {
          test: [/\.js$|.jsx$/],
          exclude: [/node_modules/],
          loader: 'babel-loader',
          options: {
            plugins: [
              ['@babel/plugin-transform-runtime'],
            ],
            presets: [
              ['@babel/preset-env', {
                targets: {
                  browsers: ['last 2 versions', 'safari >= 7'],
                },
              }],
              ['@babel/preset-es2015'],
              ['@babel/preset-stage-0'],
              ['@babel/preset-react'],
            ],
          },
        },

Jest

To allow the Jest tests to transpile jsx and EcmaScript 2015, I had to add this file. If you follow from here, you'll understand how I have configured it.

React Fragment

If you follow from here, you see a React component using a Fragment. Accoring to the React documentation you should be do the below: -

render() {
      return (
        <>
            <div key="myExample"></div>
        </>
      );
}

I wasn't able to get the empty brackets working, but I'd did the more verbose example below. This is not as clean or desirable but the effect is the same. No longer have to have this weird HTML element, cluttering your markup and adding no value.

render() {
      return (
        <React.Fragment key="blogContainerKey">
            <div key="myExample"></div>
        </React.Fragment>
    );
}

Implementation

For the full implementation details look here

Questions or comments below will be much appreciated and I'll try my best to answer. Happy fragmenting!