Extract a Function Component in React

Michael Chan
InstructorMichael Chan
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 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.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today