In this lesson we convert the class-based CurrencyCodePicker
component to a function component. To do so we employ the following strategy:
class
keyword to function
and remove the extends React.Component
partrender()
method in the function bodythis.
to reference methods or variablesconnect()
as-is (for now)After applying this technique we can see that we've successfully converted the CurrencyCodePicker from a class-based React component to a function component and the application should continue working as it did before.
This lesson does not use (or even reference hooks) and is meant to demonstrate the simplest case of migrating from a class
to a function
component. It's also interesting to note that connect()
continues to work fine on function components. We didn't need to touch any of the redux code.
Jamund Ferguson: [0:00] Open up the file CurrencyCodePicker.js. Change the class keyword to function. Get rid of extends and replace it with open and closed parentheses. Move the render() function to the function body and convert any other methods into function declarations.
[0:18] Next, we need to take care of the onChange handler in our select element. We can change this.onChange to reference our new onChange() function. With that in place, we can get rid of our constructor.
[0:28] Lastly, we need to take care of props. My favorite way of handling props is to inline them into our function declaration like this. We also have the currencyCodeUpdate() function we need to put in there. With that, we can get rid of this.props everywhere, and that's it.
[0:44] We've now converted the CurrencyCodePicker from a class-based component to a function component. You see that we've left the Redux stuff, including connect exactly as it was. All that stuff continues to work just fine with this new implementation of the CurrencyCodePicker. If we click on it, you can see that it continues to work as it did before.
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
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!