Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't typify mapRef.current

So I have this react component with leaflet map and TypeScript warns me on line mapRef.current.setView(coords, 13) that this is "unsafe call of an any typed value"

import 'leaflet/dist/leaflet.css';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { LocationType } from '../../mocks';
import { useEffect, useRef } from 'react';

type MapProps = {
  location: LocationType;
}

export const Map = ({ location }: MapProps) => {
  const { coords, address } = location;
  const mapRef = useRef(null);

  useEffect(() => {
    if (mapRef.current) {
      mapRef.current.setView(coords, 13);
    }
  }, [coords]);

  return (
    <div className="map">
      <MapContainer ref={mapRef} className="map__container" center={coords} zoom={13} scrollWheelZoom={false}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={coords}>
          <Popup>
            {address}
          </Popup>
        </Marker>
      </MapContainer>
    </div>
  );
};

How can I typify it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The type for the forwardRef on MapContainer is Ref<LeafletMap | null> (where LeafletMap is the Map from the leaflet module) so you can use the same in your component

import { Map as LeafletMap } from "leaflet";

// ...

const mapRef = useRef<LeafletMap>(null);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading