At the end of that post, we discussed why having unnecessary div elements entering the DOM could potentially cause problems. Well, I guess there must have been a solution to this right?

In the React release 16.2, a new feature was introduced called a React fragment. Think of this as a component that doesn’t translate to HTML.

Instead of using <div>'s to wrap the elements we use or the shorthand syntax <>.

Here below we have the typical solution to the error you get when you don’t wrap your React elements in a div.

import React from 'react'

const App = () => {
  return (
           <div> 
              <p>Hello</p>
              <p>World</p>
           </div>
      )
    }

Here’s how we’d rewrite this using React.fragment

import React from 'react'
const App = () => {
  return ( 
           <React.fragment>
             <p>Hello</p>
             <p>World</p>
           </React.fragment>
      )
    }

Now writing React.fragment can be a pain! So React also introduced the <> syntax

import React from 'react'
const App = () => {
  return ( 
           <>
             <p>Hello</p>
             <p>World</p>
           </>
      )
    }

React.fragment gets converted into regular JavaScript by a transpiler and after conversion looks like this. Something we’ve seen in a previous post!

React.createElement(React.fragment, null, ...children)

The difference is, it does not get inserted into the DOM!

#react #javascript #web-development

Why you should be using React Fragments
18.90 GEEK