Last updated: Apr 6, 2024
Reading time·2 min
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.
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.
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
.
// 👇️ 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.
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.
You can learn more about the related topics by checking out the following tutorials: