Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Return a list of elements from a functional component in React

    Tomasz ŁakomyTomasz Łakomy
    reactReact

    We sometimes just want to return a couple of elements next to one another from a React functional component, without adding a wrapper component which only purpose would be to wrap elements that we want to render.

    In this one minute lesson we are going to learn how to solve this problem by returning an array of components and as such - avoid adding unnecessary div wrappers.

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: We have a simple React component which displays a box and we can see the result over here. Suppose we'd like to be able to display more of those boxes. We're going to do one, two, and three. After we save it, the page is going to refresh with a failed to compile message because React is expecting adjacent JSX elements to be wrapped in a closing tag.

    We could fix it by wrapping all of those elements in a div tag. It's going to work just fine, but we are introducing unnecessary divs to our HTML site chart. In a small app such as this one, this is perfectly fine, but in larger applications, we should most likely avoid having unnecessary divs.

    To solve this problem, instead of returning this div, we throw an array of those div elements, those boxes. Of course, add commas. After we save it, refresh, we are going to see those elements displayed just fine. If we take a look inside of dev tools, we're going to see that because we worked on an array of elements, there is no unnecessary element wrapping those three boxes.