Search code examples
reactjsleafletreact-leaflet

How to access leaflet functionality with buttons that are not child components of a <MapContainer> with React Leaflet?


I have a basic React app where a user can click on a <Marker> and the map will zoom to the selected marker, which works as expected:

   function MyMap() {

     <MapContainer className="map"
       center = {[40, 10]}
       zoom = {10}
       zoomControl = {false}
       >
       <Markers>

         const map = useMap();

         loc.map(loc => {
           return (
             <Marker
               key={loc.properties.id} 
               position={[loc.properties.y, loc.properties.x]}
               eventHandlers={{
                 click: () => {
                   map.setView([loc.properties.y, loc.properties.x], 16)
                 }
               }}>
             </Marker>
           )
         })
       </Markers>
     </MapContainer>
    }

Now what I want to do, is replicate the map.setView() functionality to work on a button click. This button is placed in a side panel next to the map and is not a child of the <MapContainer>. Each <Marker> has a corresponding button in a side panel.

The main App code looks something like this:

function App() {
  <SidePanel>
    <Button />
  </SidePanel>
  <MyMap />
}

Is there a way I could easily access the map.setView() function from the <Marker> eventHandler and use it on a <Button> in the side panel?


Solution

  • If you can access your location outside MapContainer, there is a prop on MapContainer called whenCreated which returns map. You can use it outside of MapContainer.

    const [map, setMap] = useState(null);
    const loc = [];
    
    <MapContainer whenCreated={setMap}>
      <Markers locations={loc} />
    </MapContainer>
    <SidePanel>
      {loc.map((loc, index) => {/* Render button and add use map saved in state to attach click handler */})}
    </SidePanel>