Extract a Function Component in React

Michael Chan
InstructorMichael Chan

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

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.

Instructor: [00:00] 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.

[00:23] 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.

[00:36] 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.

[00:57] 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.