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

Learn how to create keyed fragments in React

Introduced in React v16.2.0, an empty tag (also known as a fragment) has the following syntax:

<> ... </>

This is merely a shorter syntax for explicitly declaring fragments with <React.Fragment>:

<React.Fragment> ... </React.Fragment>

Although the two syntaxes are equivalent, the key difference between the two is that the shorter syntax does not allow keys, while the full fragment syntax does.

So, in cases where we might need to add the key attribute (for example when mapping a collection) we can simply declare fragments with the full <React.Fragment> syntax instead.

To demonstrate this, let's suppose that in a collection of four navigation menu items we 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, we 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>

Hope you found this post useful. It was published . Please show your love and support by sharing this post.