React 16.0 came out back in September. Old news, right? But when it came out so long, long ago, they made a really nice change, in my opinion. You can return an array of elements from a component’s render method!
One thing that bugged me a bit when learning React, was that when you’re writing JSX, you can’t simply return a set of elements. For example, when writing html, the following sort of structure might be typical to see within the body of a document:
1
2
3
4
5
6
|
<h1>Title</h1>
<h4>Subtitle</h4>
<p>Some text</p>
<p>More text</p>
<img src="image.jpeg" alt="image description" />
<p>Even more text</p>
|
So when you’re writing a component, and want it to spit that out, it seems intuitive to just create those tags, and write it as shown above. But you weren’t allowed to do that! You had to wrap it all into a div, or span, or some kind of package. That’s very trivial to do, but at the same time, it’s annoying! I don’t necessarily want to enclose a bunch of stuff into otherwise unnecessary tags. It makes things more messy than they should be in the end, and there’s often no good reason for elements to be wrapped like that.
Thankfully, we can now return fragments! Simply wrap the JSX in brackets, and return an array of elements. So instead of throwing it all into a div, which seems more like a workaround to force it to all be technically one element, you simply add some brackets, and place commas between the arrays, indicating that you want to return each of those elements – the actual stuff you want.
The tricky thing right now is, you get a console warning, unless you assign each element a key. This has to do with how React handles arrays, and what it needs in order to identify changes or removals. For fragments in particular, it actually shouldn’t matter, but the warning will still appear unless keys are added. This isn’t so convenient, but I still like where it’s going – and the react developers said they’ll add a special fragment syntax to JSX so it doesn’t require keys. I’m looking forward to that!