Advanced use case of Reactjs Fragment.
Advanced use case of Reactjs Fragment.

Reactjs Advanced

Advanced use case of Reactjs Fragment

Understand advanced use of Reactjs Fragment.

Reactjs fragment component helps to wrap multiple elements and turn them into one element.

Reactjs component can only return one element, but by using a Fragment, you can group multiple elements together and then return them as a group:

<Fragment>, often used via <>...</> shorthand syntax in reactjs.

Grouping elements with <Fragment>component does not affect the resulting DOM; it works like a regular component.

Most of the time, we use empty <>...</> JSX tag as shorthand for <Fragment></Fragment>.

export function Card({ post }: { post: Post }) {
return (
<>
...
</>
)
}

Advanced Use case

In this tutorial, we talk about react.js advanced use cases. Most developers face the following problem in reactjs. Reactjs developers use an extra div HTML to add reactjs keys when we use a loop in reactjs such as map(), etc.

export async function Blog() {
const data: Posts = await getFetchPost(); // fetch data
const { posts } = data

return posts.map((post: Post) => {
return (
<>
<div key={post.id} > {/* Extra key */}

<h2 className="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
{post?.title}
</h2>
<p className="mb-5 font-light text-gray-500 dark:text-gray-400">
{post?.body}
</p>

</div>
</>
)
})
}

To solve this problem, you do not have to define an extra div for the key in reactjs. You can do that with a reactjs fragment.

The Fragments have a key option where we can pass our unique key for reactjs.

import { Fragment } from 'react';

export async function Blog() {

const data: Posts = await getFetchPost(); // fetch data

const { posts } = data

return posts.map((post: Post) => {
return (
<Fragment key={post.id}>
<h2 className="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
{post?.title}
</h2>
<p className="mb-5 font-light text-gray-500 dark:text-gray-400">
{post?.body}
</p>
</Fragment>
)
})
}

Note

  • You cannot pass the key with the following syntax: <>...</>.
  • To pass the key, you must import a fragment from ‘react’ and render it explicitly with the following syntax: <Fragment></Fragment>

What is the difference between <Fragment>...</Fragment> vs <>...</>?

You can use reactjs fragment shorthand syntax <>...</> in those cases where you do not need to pass a key.

If you use the reactjs fragment inside the loop where you must pass a key inside the reactjs fragment, you can use <Fragment></Fragment> syntax.

To learn more about frontend developers, reactjs, nextjs, and Linux stuff, follow the frontend web publication on Medium and other updates. You can also follow me on Twitter (X) and Medium.

--

--

Rajdeep Singh
FrontEnd web

JavaScript | TypeScript | Reactjs | Nextjs | Rust | Biotechnology | Bioinformatic | Frontend Developer | Author | https://linktr.ee/officialrajdeepsingh