visgl / visgl/react-map-gl

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

Open
#1,998 0 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
TypeScript
Stars
8.5k
Forks
1.4k
Avg merge
5d 17h
Merged PRs (30d)
3

Description

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: react-map-gl@7.0.19
  • Map library: mapbox-gl@2.10.0
  • Browser: Chrome v105.0
  • OS: macOS 12.15.1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the GeolocateControl documentation example and the linked CodeSandbox reproduction, then compare it with the Map onLoad workaround. Trace when the ref callback runs relative to the control being added to the map. Done means triggering via the documented ref on mount behaves like a click without logging the warning.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.