← 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. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

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

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

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

Can you stay a bit longer?