Accessing map reference using React-google-maps v6+

Viewed 1969

The newest changes to react-google-maps seem to have removed the mapHolderRef property to access the map instance. Looking at the new component changes, it looks like they call internal constant context references, but it doesn't seem like those should be used/are easily exposed.

Before the newest version, I was able to do something like below to add a custom control to the map:

paintControl(props) {
  const { rendered } = this.state;
  const position = props.position || google.maps.ControlPosition.TOP_CENTER;
  const map = props.mapHolderRef.getMap(); // This no longer works
  const controlElement = React.createElement(props.customControl, { map, ...props });

  ReactDOM.render(controlElement, this.customControlDiv);
  this.customControlDiv.style.zIndex = this.props.zIndex || 1;

  if (!rendered) {
    this.setState({ rendered: true }, () => {
      map.controls[position].push(this.customControlDiv);
    });
  }
}

There was notes in the 6.0 release mentioning this mapHolderRef property is no longer accessible through props, but through context instead. I have tried getting that to work, but can't seem to figure it out.

I am currently using the onMapLoad callback to get the react map instance, but getting to the actual google map reference seems to be missing. I have been able to get a usable reference by doing:

const map = props.mapHolderRef.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;

But that seems really janky and incorrect. It's also creating multiple controls instead of maintaining the one, so something is off there. Not sure if there's something in the new docs that I missed or if this simply isn't available in the new version.

Has anyone had luck getting custom controls or components to work with the new react-google-maps version?

Thanks for your help!

2 Answers
Related