onoya.dev

Render Multiple Components in ReactJS with Fragments

Render Multiple Components Prior to Version 16

Prior to version 16, the easiest way to render multiple components was by wrapping the components in a single parent element.

import React, { Component } from 'react'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; class SampleComponent extends Component { render() { return ( <div> <ComponentA>, <ComponentB>, <ComponentC>, </div> ); } } export default SampleComponent;

But with this method, you are adding an unnecessary extra node to the DOM.


Version 16

In Version 16, we were able to return an array of elements from a component’s render method:

import React, { Component } from 'react'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; class SampleComponent extends Component { render() { return [ <ComponentA key="A">, <ComponentB key="B">, <ComponentC key="C">, ]; } } export default SampleComponent;

As you can see, we have to always add a key to each element since it’s an array. This is to avoid the key warning.


Version 16.2

In Version 16.2, there was an addition of special syntax in JSX that doesn’t require keys, which is the Fragment.

Fragment lets you group a list of children without adding extra nodes to the DOM:

import React, { Component, Fragment } from 'react'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; class SampleComponent extends Component { render() { return ( <Fragment> <ComponentA>, <ComponentB>, <ComponentC>, </Fragment> ); } } export default SampleComponent;

It also has a short syntax version, but is only supported with Babel v7.0.0-beta.31 and above:

import React, { Component } from 'react'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; import ComponentC from './ComponentC'; class SampleComponent extends Component { render() { return ( <> <ComponentA>, <ComponentB>, <ComponentC>, </> ); } } export default SampleComponent;

As for attributes that we can pass to Fragments, it only supports the key attribute at the time of writing. But as per the docs, it may support additional attributes in the future:

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.


Sources: https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html