Day 3 - What are fragments in React?

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>
  );
}

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>
  );
}

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