react-map-gl icon indicating copy to clipboard operation
react-map-gl copied to clipboard

[Bug] Unable to trigger `GeolocateControl` ref on mount

Open chrissantamaria opened this issue 3 years ago • 0 comments

Description

Triggering a GeolocateControl via a ref on mount fails and logs a warning:

Geolocate control triggered before added to a map

This is based on the example provided in GeolocateControl's docs:

import * as React from 'react';
import Map, {GeolocateControl} from 'react-map-gl';

function App() {
  const geolocateControlRef = React.useCallback((ref) => {
    if (ref) {
      // Activate as soon as the control is loaded
      ref.trigger();
    }
  }, []);

  return <Map><GeolocateControl ref={geolocateControlRef} /></Map>;
}

Expected Behavior

GeolocateControl is triggered as if it were clicked, resulting the map flying to a user's location

Steps to Reproduce

https://codesandbox.io/s/angry-dream-ig4c1o (same approach as the docs example)

Workaround

Obtaining a ref via useRef and calling trigger in Map's onLoad callback works, though I'm not sure if there's any downsides to this approach. Something like:

import * as React from 'react';
import Map, {GeolocateControl} from 'react-map-gl';

function App() {
  const geolocateControlRef = React.useRef(null);

  return (
    <Map
      onLoad={() => {
        geolocateControlRef.current?.trigger();
      }}
    >
      <GeolocateControl ref={geolocateControlRef} />
    </Map>
  );
}

Environment

chrissantamaria avatar Sep 23 '22 17:09 chrissantamaria