Enjoy free content straight from your inbox 💌
00:00
Just like any well maintained library react has evolved over time. And one great feature that it got is the support for fragments. So in this lesson, we will look at what is the motivation for this feature and how it works in React. So let's go. But because we return what our component wants to render as a return value within JavaScript, conventionally it must be a single value. For example, it can be a single div containing some simple text. However, if you want two divs side by side for this particular component, we cannot do that because then we would be returning two values
00:33
and you could return an array. But two values by themselves are not something that makes sense and therefore are a compile error. Now a simple solution can be to wrap it in another container, and that's what people used to do before fragments. So we could contain these two devs within another div, and now we are back to returning a single element. Now of course, if you were to inspect the running application right now, you can see that the two divs, hello and how are you today are being wrapped by this new container diviv. This wrapping in other containers is not ideal
01:05
because this can break existing CSS selectors and that is why fragments were introduced. The fragment is the special component that is provided by React, which we can bring in from the react module. And then instead of wrapping the two divs with another div, we can wrap them in this fragment component. And now within the dev tools, you can see that that annoying container div goes away and our component is rendering two simple diffs as we wanted to do initially. Now, this is actually such a useful and powerful feature that there is a special syntax in JSX. For this purpose, we can actually get rid
01:40
of the fragment component that we just imported and create JSX tags without any element names. And this is an implicit import to the fragment component that we saw previously. So this is exactly the same at runtime as the code before, but this is just the more conventional, neat shorthand syntax for creating fragments. As always, thank you for joining me and I'll see you in the next one.