Kyle
Kyle

Reputation: 190

TypeScript type for MapboxGLjs React ref hook

I'm trying to add a source for my mapboxgl map which I am writing in React with hooks and TypeScript.

export default function App() {
  const mapContainer = React.useRef<any>(null);
   const map = React.useRef<any>(null);
   const [lng, setLng] = React.useState(-74.0632);
   const [lat, setLat] = React.useState(40.7346); 
   const [zoom, setZoom] = React.useState(12);

  React.useEffect(() => {
    if (map.current) return; // initialize map only once
    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [lng, lat],
      zoom: zoom
    });
    map.addSource('property-data', {
      type: 'geojson',
      data: 'path/to/data.geojson'
    });
    
  });

I am encountering the following error:

Property 'addSource' does not exist on type 'MutableRefObject'

What type then should I use if not any?

Upvotes: 2

Views: 5560

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You want to keep a mapboxgl.Map in the ref, and you also want it to be null before it's initialized. So that means your ref type is:

const map = React.useRef<mapboxgl.Map | null>(null);

This is good to fix (it's good to eliminate all uses of any), but that has nothing to do with the error you are getting.

When you have a ref, you always access what it's referencing via the current property. So you simply need to change your last lines to this:

map.current.addSource(/* ... */)

Working example playground

Upvotes: 6

Related Questions