React Fragments

Photo by Denys Nevozhai on Unsplash

Simply put, fragments allow components to return sibling elements.

If you were to return this jsx inside of a component

const component = () => (
<p>Paragraph 1</p>
<p>Paragraph 2</p>
);

You would see an error similar to this that states: “Adjacent JSX elements must be wrapped in an enclosing tag.”

Adjacent JSX Elements must be wrapped in an enclosing tag.

Why can’t I just use a div?

You can use a div , but unless you’re using it to apply styling to the group of elements being returned, using a div is overkill. It’s not necessary, because React provides fragments, which can in someways be thought of as a div that does not actually render anything in the DOM.

What are the <> in React?

The <> is just shorthand jsx syntax for a React fragment. So you can simply use:

const component = () => (
<>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</>
);

For more info check out the official documentation: https://reactjs.org/docs/fragments.html

--

--

--

Web/Mobile Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeff Lombard

Jeff Lombard

Web/Mobile Developer

More from Medium

React Router V6

1. State-props

How to make a table in React with Hooks