React Fragment Short Syntax Hack

react
fragment
short syntax

In React, a common pattern is to return a list of children. However, adding a wrapper div to your result can mess up your styling or you might not want an extra node in the DOM. This is where React Fragments come in handy.

React Fragments let you group a list of children without adding extra nodes to the DOM. And the short syntax <> is a sweet syntactic sugar for <React.Fragment>. Here's how to use it:

function ExampleComponent() { return ( <> <ChildA /> <ChildB /> <ChildC /> </> ); }

In the code snippet above, ExampleComponent is returning multiple children, ChildA, ChildB, and ChildC, without a wrapper div, thanks to the <> short syntax.

Remember, while the short syntax is handy, it does not support keys or attributes. Use <React.Fragment> when you need them.

Keep experimenting and happy coding! You can find me at @samuellawrentz on X.
00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?