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

    Extract a Function Component in React

    Michael ChanMichael Chan
    reactReact
    javascriptJavaScript

    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.

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