Instructor: First, let's create a new React app with npm init react-app and the name of your application. I'll call it cra2-fragment. Immediately see the entity app after it's bootstrapped.
Once everything's created, then open up VS Code with code ., and start the React dev server with npm start. In this case, I've tweaked the code somewhat from the base createReactApp code. In our app.js file, I'm using a CSS grid for our layout with a header, nav, main, and a footer. You can see the rendered output here on the right.
Going to our app.css. file, you can see where I'm defining our grid template areas. I've selected various elements on the page to indicate their designated grid area name, head, nav, main, and footer. As is commonplace when an application gets large, or we want to split out things into components, we'll refactor our code somewhat.
For example, we might want to create a new content React component that contains our nav and main elements, and then insert our new component where it should go. That seems like a logical thing to do, but if we save our work, you'll see that our layout on the right breaks.
If we inspect the DOM in dev tools, you'll see that indeed our nav and main elements are wrapped in a div, which makes sense, since our React component on the left has a div wrapper around them. Don't we have to have some common parent to render?
That was true for a long time, but as of React version 16.2, there's a new component called a fragment that lets you wrap a group of children without adding an extra node to the DOM. Let's replace our div with react-fragment and save.
Voila, our layout is fixed again. We no longer have an unnecessary wrapping div breaking our layout. Another way we could have coded this is to import the named fragment export from React, much like we're doing with component.
By doing so, we could remove the react-period portion of our fragment. If we save, it still works. Going one step further, Babel version 7.0added support for another more terse version of fragment, known as the short syntax.
We could remove the word fragment completely, and less than/greater than represents a fragment under the covers, a non-wrapping component. We'll save our code, and like before, our layout still works.
In review, feel free to use the fragment component if you need to return multiple elements, and you don't want to add an extra node to the DOM. If you're using Babel version 7.0or above, like in createReactApp 2.0then you could utilize the new short syntax of fragment.