UI/UX Design

What are React Fragments and why you should use them

Fragments were introduced in React 16 but its support was improved a lot in the latest version which is 16.2.0 at the moment.

What are React Fragments?

Fragments allows you to group a list of children without adding extra nodes to the DOM and it looks just like empty JSX tags:

  
  

render() {
  return (
    <>
      <FirstComponent />
      <SecondComponent />
      <ThirdComponent />
    </>
  );
}

  

 
Under the hood this converts to <React.Fragment /> which means that you can use <Fragment /> the same way you’d use any other element, without changing the way you write JSX

  
  

const Fragment = React.Fragment;

<Fragment>
  <FirstComponent />
  <SecondComponent />
  <ThirdComponent />
</Fragment>

  

 
Please note that the <></> syntax does not accept attributes, including keys so you will have to use the <Fragment /> syntax.

 
In the earlier versions of React you would have to do something like:

  
  

render() {
  return (
    // irrelevant div element
    <div>
      <FirstComponent />
      <SecondComponent />
      <ThirdComponent />
    </div>
  );
}

  

 
Since React 16, you can also return an array of elements from a component’s render method like this:

  
  

render() {
  return [
    <div key="first-component">First Component</div>,
    <div key="second-component">Second Component</div>,
    <div key="third-component">Third Component</div>
  ];
}

  

 
Please note that:

  • You’ll need to add a key to each element to avoid the key warning. You won’t need a key in the JSX version.
  • The children in the array must be separated by commas.
  • The strings should be wrapped in quotes.

Andy

UI/UX Designer & Front-end Engineer based in Dublin currently working @IBM.
I write about: UI/UX Design, Javascript, HTML, CSS, React JS and React Native

Add comment