← react hacks / react / fragment-short-syntax.md

React Fragment Short Syntax Hack

Learn to use the React Fragment Short Syntax (<>), a concise and efficient way to group a list of children without adding extra nodes to the DOM.

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!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

00:00

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

Can you stay a bit longer?