Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use React Fragments to make your DOM tree cleaner


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



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.