Migrate a React class component to a Function component (React-google-maps) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Migrate a React class component to a Function component (React-google-maps) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m using the react-google-maps library for a project and i found a perfect example for what i need. It is the code below and as you can see it is a class component.

class Map extends Component {
  constructor(props){
    super(props);
    this.map = React.createRef();
  }

  render() {
    const MyGoogleMap = withScriptjs(
      withGoogleMap(props => (
        <GoogleMap
          ref={map => {
            this.map = map;
          }}
        />
      ))
    );

    return(
      <MyGoogleMap />
    );
  }
}

export default Map

I want to migrate this class in a function component.

The lines i don’t know how to implement to a function components is

this.map = React.createRef();

and

ref={map => { this.map = map }}

Answer

In a Function Component, you use a useRef hook.

There is a subtle difference between useRef & createRef: refer to this post.
What’s the difference between `useRef` and `createRef`?

Make sure to rid of this. in a function component.

function Map() {
  const mapRef = useRef();

  const MyGoogleMap = withScriptjs(
    withGoogleMap(props => <GoogleMap ref={mapRef} />)
  );

  return <MyGoogleMap />;
}
We are here to answer your question about Migrate a React class component to a Function component (React-google-maps) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji