Migrate a React Class Component to a Function Component

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we convert the class-based CurrencyCodePicker component to a function component. To do so we employ the following strategy:

  1. Change the class keyword to function and remove the extends React.Component part
  2. Place the contents of the render() method in the function body
  3. Convert all other methods on the class to stand-alone functions
  4. Remove the constructor function
  5. Inline any props into the function declaration using object destructuring
  6. Get rid of any use of this. to reference methods or variables
  7. 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.

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.