DEV Community

Cover image for Day 3 - What are fragments in React?
C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at blog.sanjaybabu.dev on

Day 3 - What are fragments in React?

As you may already know, A React component can return only 1 node. So if we had multiple elements to return, then we have to simply wrap a <div> around them and return a single element like below.

render() {
  return (
    <div>
      <LeftItem />
      <RightItem />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

This affected the sematic nature of HTML and resulted in react apps having lots of unwanted nested components. So in order to solve this, Fragments was introduced in react v16.2. Fragments are syntax that allows a React component to return multiple elements without wrapping them in an extra DOM node.

Now we instead of adding <div> like before, we can use <React.Fragment>

render() {
  return (
    <React.Fragment>
      <LeftItem />
      <RightItem />
    <React.Fragment>
  );
}

Enter fullscreen mode Exit fullscreen mode

Note that there is also a shorthand way to create Fragments. We can simple use empty tags <> & </> instead of <React.Fragment>

Top comments (0)