How to add a key prop to a React Fragment

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# 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;

add key prop to react fragment

The code for this article is available on GitHub

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;

importing fragment element from react

The code for this article is available on GitHub

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

Make sure the key prop is unique, otherwise, you'll get the Encountered two children with the same key warning.

You should also not try to access the key property, otherwise, the warning Key is not a prop. Trying to access it will result in undefined is raised.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.