This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Use React Fragments to make your DOM tree cleaner

    Akash GuthaAkash Gutha

    In this lesson, we will look at Fragments and how they are useful in achieving a cleaner DOM structure without additional empty div elements.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 I have a basic React project set up over here, and the app contains a simple component that is the header/footer component. The header/footer component is a stateless component which returns this one, single big division that contains two small divisions, with header and footer.

    00:14 If you look at our tree structure, you can see that we have one extra division, that is this division, that is enclosing the header and footer. It's not really required. Let's just go ahead and delete this, and see what happens.

    00:30 You can see that it's failed, and the error that it's given us, syntax error, additional JSX elements must be wrapped in an enclosing tag. That means this header and this footer are two JSX elements that additional, and both of them should be enclosed into one single tag.

    00:46 That is why we had the original division in place. That means this return function should only return one single component, or one single HTML element. One possible solution that you have is just remove this.

    01:01 We can actually change this is an array, where each division is an element in the array. Then this will work perfectly fine. If you check the console, you can see that we have an error saying that each child in an array iterator should have a unique key code.

    01:19 If we provide them with unique keys, this problem will go away. Let's do this, key B. Then once we reload it, you can see that it no longer throws the errors, since each element has its own key. It is not a very elegant solution.

    01:38 To tackle this, we are going to use the fragment component, which can be used instead of the division element. This will act as the enclosing tag, but once it reloads, you can see that it's working perfectly fine. Also, we don't have that weird extra division tag.

    01:56 Now, the best thing about fragments is that you can also pass in props into this. Here, we can say props.name, and we can possibly pass in name over here. Then say Akash. It works perfectly fine.

    Discuss

    Discuss