react-map-gl
react-map-gl copied to clipboard
[Bug] Unable to trigger `GeolocateControl` ref on mount
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
- Framework version: [email protected]
- Map library: [email protected]
- Browser: Chrome v105.0
- OS: macOS 12.15.1