React fragments

Let’s say that we want to set to elements side-by-side in a React component:

function columns() {
	return (
		<th>First column<th>
		<th>Second column<th>
	)
}

If you used like this, React will complain about this

Adjacent JSX elements must be wrapped in an enclosing tag....

So, we could wrap the code inside a <div>, but this would result in an invalid HTML (in our case), and honestly, you wouldn’t want to add more elements Than the ones you really need. That’s what the React fragments are for. They allow you to wrap a group of children side-by-side, and they won’t appear in the resulting HTML. You can use it like this:

function columns() {
	return (
		<React.Fragment>
			<th>First column<th>
			<th>Second column<th>
		</React.Fragment>
	)
}

Or with the shorthand, like this

function columns() {
	return (
		<>
			<th>First column<th>
			<th>Second column<th>
		</>
	)
}

And the result HTML will be:

<th>First column<th>
<th>Second column<th>

You can add a key prop when you want to use them inside a map. For more information, you can check Fragments – React

Luis Güette
Luis Güette

I'm a tech guy and I love to make software products with the last technology trends.

© 2022 TAE Control Solution. All rights reserved.