Course lesson
Migrate a React Class Component to a Function Component
In this lesson we convert the class-based CurrencyCodePicker component to a function component. To do so we employ the following strategy:
- Duration
- 1 min
- Access
- Free
- Transcript
- Available
In this lesson we convert the class-based CurrencyCodePicker component to a function component. To do so we employ the following strategy:
- Change the
classkeyword tofunctionand remove theextends React.Componentpart - Place the contents of the
render()method in the function body - Convert all other methods on the class to stand-alone functions
- Remove the constructor function
- Inline any props into the function declaration using object destructuring
- Get rid of any use of
this.to reference methods or variables - Leave the redux boilerplate like
connect()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.