April 26, 2018

Use of React.Fragment

React developers know what does it mean when they saw this error:

Adjacent JSX elements must be wrapped in an enclosing tag

It’s simply fixed by adding <div> tags between the element. At least it used to be, until I saw React.Fragment in a blog and read the new official documentation of React. It’s as simple as replacing <div> tag with React.Fragment:

import React, { Fragment } from 'react';

const MyFragment = () => (
    return (
            <div>First div</div>
            <div>Second div</div>

export default MyFragment;

The use of <Fragment> will not render extra <div> tag, which is a good news in certain case of styling.

© 2022, Built with Gatsby