Can't typify mapRef.current

Advertisements

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?

>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);

Leave a ReplyCancel reply