Fragments

Loading "Fragments"
πŸ¦‰ One feature of JSX that you'll find useful is called "React Fragments".
React Fragments allow you to group multiple elements without adding an extra DOM node. This lets you return multiple elements side-by-side from a component without needing a wrapper div. It's useful for avoiding unnecessary markup that could affect styling or layout.
We have currently the following code:
<div className="container">
	<p>Here's Sam's favorite food:</p>
	<ul className="sams-food">
		<li>Green eggs</li>
		<li>Ham</li>
	</ul>
</div>
We want to do the same thing as above, except we don't want the container div. So, we want to just create:
<p>Here's Sam's favorite food:</p>
<ul class="sams-food">
	<li>Green eggs</li>
	<li>Ham</li>
</ul>
In React, we do this with <React.Fragment>. Replace the <div className="container"> with a fragment and inspect the DOM to notice that the elements are both rendered as direct children of root.
πŸ’° TIP: Fragments are common enough that there's a syntax shortcut for them. You can open with <> and close with </>, so:
element = <React.Fragment>this is in a fragment</React.Fragment>
// is the same as:
element = <>this is in a fragment</>
πŸ‘¨β€πŸ’Ό We want to get rid of the <div className="container"> we have in there, but we need to keep the <p> and <ul> next to each other. Figure out how to make that work.
πŸ’― As a little extra part of this, try to figure out why <React.Fragment> is needed at all. Might help if you look at what this looks like using createElement rather than JSX. As I said, understanding how JSX compiles to createElement really helps improve your capabilities with JSX!

Please set the playground first

Loading "Fragments"
Loading "Fragments"

Access Denied

You must login or register for the workshop to view the diff.

Check out this video to see how the diff tab works.