Day 3 - What are fragments in React?

sanjaybabu

C K Sanjay Babu

Posted on May 3, 2022

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>

πŸ’– πŸ’ͺ πŸ™… 🚩
sanjaybabu
C K Sanjay Babu

Posted on May 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related