How to Add a Key to an Empty Tag in React?

The empty tags (<>...</>) in react do not support keys or attributes. However, since they're meant as a shorter syntax for <React.Fragment>, you may simply use the full syntax instead when you need to add an attribute (such as the key attribute).

To demonstrate this, let's suppose that in a collection of four navigation menu items you need the logo to appear in the center visually; the code for that with empty tag syntax might look something like the following:

<ul>
    {navItems.map((item, i) => (
        // without the `key` attribute, React will trigger a warning
        <>
            <MenuItem { ...item } />
            {i === 1 && <Logo /> }
        </>
    ))}
</ul>

In such cases, react will show a warning that the key attribute is not present (since the empty tag syntax does not support keys). To make this work, you will have to substitute it with the full <React.Fragment> syntax like so:

<ul>
    {navItems.map((item, i) => (
        <React.Fragment key={i}>
            <MenuItem { ...item } />
            {i === 1 && <Logo /> }
        </React.Fragment>
    ))}
</ul>

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.