Become a member
to unlock all features

Level Up!

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


    Extract a Function Component in React

    Michael ChanMichael Chan

    Extracting new function components in React applications is something we do several times a day. This video illustrates how to use errors to focusing your component extractions and component refactoring.



    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




    Instructor: To create a new function component in React, I like to visually select the code that I want to extract, then cut it. I then replace it with the code that I would like to exist, in this case, a Button component. Now it doesn't exist, so we'll see an error, and that's great. The error can help lead us to a solution.

    Now I go back in my code and create a function with the name of the undefined component, Button. We'll take no arguments and return that which we had deleted.

    Now, from here, I'll simply repeat this process for anything that needs to be customized, for example, children, which we will get from the undefined props. Then, once props is defined, updating the call of our component to fulfill that API.

    To make our component particularly rugged, I'll use JSX spread attributes to spread out all of the props so that any IDs, classes, data attributes, or whatever get sent along and rendered as this Button.