Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer> [duplicate]
Asked Answered
D

3

8

I'm using react-leaflet and I added a marker with an event Handler on click to zoom to this marker , but when I try to use const map=useMap() all I get is this error => :

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

There might be similar questions but none have answers, can anyone please help with this? This is my code:

const map = useMap()
 return (
        <div>
          <MapContainer
            className="leaflet-container"
            center={[33.8735578, 35.86379]}
            zoom={9}>

            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

            <Marker
              icon={port}
              eventHandlers={{
                click: (e) => {
                  map.setView(e.latlng, 14);
                },
              }}
              position={[33.90757548098519, 35.51700873340635]}
            ></Marker>
          </MapContainer>

Thanks!

Digit answered 13/1, 2022 at 10:56 Comment(0)
D
8

well I solved it by making a separate component for the marker and implement the useMap() in it and it worked as so :

import React from "react";
import { Marker, useMap } from "react-leaflet";

export default function Markerwhatever(props) {
  const map = useMap();

  return (
    <div>
      <Marker
        icon={props.icon}
        position={[33.91907336973602, 35.51552625946782]}
        eventHandlers={{
          click: (e) => {
            map.flyTo(e.latlng, 14);
          },
        }}
      ></Marker>
    </div>
  );
}

Digit answered 13/1, 2022 at 11:26 Comment(1)
could u give more info on this?Wolfhound
D
2

If you got the issue

No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

after upgrading react-leaflet and/or leaflet, you should remove and re-add the plugin package (in my case the marker cluster plugin) because the upgrade may have create conflict in the packages versions.

Debbiedebbra answered 12/7, 2023 at 8:24 Comment(0)
A
-1

If useMap is not imported from react-leaflet, then you are using older verions. v2 you need to run npm i @react-leaflet/core if issue still persist remove node_modules and clear cache npm cache clear --force and install npm i

Althing answered 12/7, 2023 at 7:44 Comment(2)
I am having the same issue, and this didn`t help...Herbage
Please check leaflet version and react-leaflet version. note: react >=18 doesnot supports less than leaflet v3Althing

© 2022 - 2024 — McMap. All rights reserved.