Skip to content

Instantly share code, notes, and snippets.

@jonidelv
Last active February 9, 2019 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonidelv/412099262721f9cee086228611f13bf8 to your computer and use it in GitHub Desktop.
Save jonidelv/412099262721f9cee086228611f13bf8 to your computer and use it in GitHub Desktop.
Fragments in React and <>

Fragments in React

How to use React.Fragment or its shorthand <> to prevent the use of divs


In React, components could only display a single element that could contain other elements. So you colud't do this.

const MyName = props => {
  return (
    <h1>{props.name}</h1>
    <h2>{props.lastName}</h2>
  )
}

You need to wrapp in one containing element like a div, so React components can only return one child.

const MyName = props => {
  return (
    <div>
      <h1>{props.name}</h1>
      <h2>{props.lastName}</h2>
    </div>
  )
}

Because of this when you inspect the code is full of unnecessary div elements that makes the code looks messy and hard to read.

Fragment to the rescue

Fragment is a component you can import from React, which will replace those unnecessary div's.

import React, { Fragment } from 'react'

const MyName = props => {
  return (
    <Fragment>
      <h1>{props.name}</h1>
      <h2>{props.lastName}</h2>
    </Fragment>
  )
}

So when the page renders, you won't se the divs anymore just the elements that contains the data

<>

You can reduce the code using <>, is equivalent to using <Fragment />

const MyName = props => {
  return (
    <>
      <h1>{props.name}</h1>
      <h2>{props.lastName}</h2>
    </>
  )
}

The only caveats is that if you want to give the fragment a key, you have to use <Fragment>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment