2

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Alex coming to my rescue again. I caught that “current” mistake shortly after posting. 🙄 Thanks for your help again, Alex!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.