1

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 }}

dance2die
  • 35,807
  • 39
  • 131
  • 194
iNemesis
  • 119
  • 1
  • 8

1 Answers1

0

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 />;
}
dance2die
  • 35,807
  • 39
  • 131
  • 194