React Fragments: All you need to know

1–2 minutes

read

<p class="has-drop-cap" value="<amp-fit-text layout="fixed-height" min-font-size="6" max-font-size="72" height="80">A fragment is a common pattern in React which is used to return multiple elements. A fragment is a common pattern in React which is used to return multiple elements.

Since in react we have to group jsx under a some parent. Fragments let us group a list of children without adding extra nodes to the DOM. So instead of a div or span or any element we can use React Fragment which will not create any extra node in the DOM. Let me show an example that will show how we can use React fragments.

Let us suppose we have two child elements, lets say ChildA and ChildB, now

<ChildA /> and <ChildB />

So to wrap them we would have used a div in a way such that-

render() {
  return (
    <div>
      <ChildA />
      <ChildB />
    </div>
  );
}

But this would have created a useless div which is not required so we can use react fragment in this way.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
    </React.Fragment>
  );
}

These react fragments will wrap ChildA and ChildB and thus solve this problem.

Short Syntax
We can also use Fragment’s short syntax, which is just an empty container.

render() {
  return (
    <>
      <ChildA />
      <ChildB />
    </>
  );
}

Keyed Fragments

We can add key as an attribute to the react fragments, so when we are using map then we can add unique key to the fragments. Example-

function sample = (props) => {
  return (
      {props.map(item => (
        <React.Fragment key={item.id}>
           <ChildA />
           <ChildB />
        </React.Fragment>
      ))}
  );
}

Without the key, React will fire a key warning, so with Fragments we can use key also.

This is all about React Fragments, thanks for reading.

Leave a comment