React: Converting a Class Component to a Functional Component

Amanda Walker Brubaker
2 min readDec 8, 2020

--

If there ever comes a time when you need to have local state in your functional component, the time has come to transition over to Class Component, or add Hooks. If you’re not ready to start using Hooks just yet, then here’s how you can make the switch. You’ll see a lot of legacy code will use Functional and Class Components, so it’s a good thing to know.

Functional Components are basic functions that accepts props as an argument. There is no render method, so they return JSX code directly.

A Functional Component Example

I built a Dog Walking app called Bark! that connects dog walkers and owners. I wanted to add a button where Dog Walkers could rate the dogs they walked on a “Good Dog-o-Meter scale” after a walk. Ideally this would be a quick form after a dog walk the Walker would fill out with a 1–5 drop down rating, but for our purposes, we’ll need to convert over to a Class Component either way.

A Class Component with State

If you look closely, you’ll see the Class Component above is numbered. Here are the steps you need to follow to convert to a Class Component.

  1. Import the Component from React and extend Component
  2. Change function to class. If you were using ES6 arrow function originally, change it to look like the above.
  3. Since we no longer have a function accepting props, we’ll need to initialize our class and new state with a constructor. This will accept the props passed in from the parent component and pass that in to super(props). This will give us access to calling this.props within the constructor, but as long as you pass props into the constructor argument, you’ll be able to use this.props outside the constructor.
    Note: This is also a good place to set your initial state.
    Technically you have a fully functioning Class Component right now and steps 4 and 5 are bonus!
  4. Use your state. Here I created a button, that upon a click will increase the ‘Good Dog-o-Meter’ by 1. This button has a click event that will invoke the handleLikes function.
  5. Continually update your state with setState. Any time the button is clicked there will be a change in state.

That’s it for converting a Functional to a Class Component. If you have any questions, feel free to ask away. I’m always happy to reach out.

Until the next time, keep your head up and peace!

--

--

Amanda Walker Brubaker
Amanda Walker Brubaker

No responses yet