How to add a key prop to a React Fragment

avatar

Borislav Hadzhiev

Last updated: Apr 18, 2022

banner

Photo from Unsplash

Add a key prop to a React Fragment #

Use the more verbose syntax of fragments to add a key prop to a React fragment, e.g. <React.Fragment key={key}>. The more verbose syntax achieves the same result - groups a list of elements without adding extra nodes to the DOM.

App.js
import React from 'react'; const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; return ( <div> {arr.map((element, key) => { return ( <React.Fragment key={key}> <h2>key: {key}</h2> <h2>element: {element}</h2> <hr /> </React.Fragment> ); })} </div> ); }; export default App;

We used the more verbose syntax for React fragments to be able to add a key prop to the fragment.

Fragments are used when we need to group a list of children without adding extra nodes to the DOM.

If you use the shorthand syntax for fragments <> </>, you won't be able to pass any props to the fragment.

You can also import the Fragment element from react to not have to access it as React.Fragment.

App.ts
// 👇️ only import Fragment import {Fragment} from 'react'; const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; return ( <div> {arr.map((element, key) => { return ( <Fragment key={key}> <h2>key: {key}</h2> <h2>element: {element}</h2> <hr /> </Fragment> ); })} </div> ); }; export default App;

This code sample achieves the same result, but instead of importing the React namespace object, we only import the Fragment element.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.