I know that, in React, you can't add a key to an empty fragment:
// will result in an error
< key={'foo'} >
{...}
</>
Instead, you need to use React.Fragment
:
// works fine
<React.Fragment key="foo">
{...}
</React.Fragment>
The React documentation notes this, but it doesn't explain why, and I'm curious. Is it a limitation in JSX? Or is it a design decision that React made for some reason?
Edit: I found this post. It sounds like Fragment
came first, then <>
followed (and was upstreamed to JSX). But why didn't they make it so it could be parameterized? Just curious on the context of the decision and if there's an underlying reason, since I don't understand JSX all that well.
This was actually a question that I also had in mind. After asking around from people who made the pull requests for keyed fragments and snooping around the source code I think I have the answer.
I believe that it would be easy to add a key to the shorthand syntax as well since they get reconciled the same way. However if we were to add a key in the shorthand syntax it would be like as such:
<key="1">foo</>
Now this leads to a lot of confusion, is key another tag? if not, then what if JSX adds another <key></key>
tag. That will raise even more confusion. Which is why all shorthand syntax do not support attributes.