PaulLeCam / react-leaflet

React components for Leaflet maps
https://react-leaflet.js.org
Other
5.19k stars 887 forks source link

[question] Change Center of map if state changes #1101

Open FleetAdmiralJakob opened 1 year ago

FleetAdmiralJakob commented 1 year ago

How can I make that if I change a state that stores the coordinates in a higher component and pass the state as a prop to the map component. How can I make that the center of the map changes if the state changes?

KarthikYerra1 commented 7 months ago

use useRef hook.

//Code const mapRef = useRef(null);

useEffect(() => { if (mapRef.current && lat !== undefined && lng !== undefined) { mapRef.current.setView([lat, lng], mapRef.current.getZoom()); } }, [lat, lng]);

<MapContainer center={[lat, lng]} zoom={13} ref={mapRef}

{...your code}

//Code

Explanation:

  1. Use useRef hook and create an instance reference of the map.
  2. use useEffect hook to update the map position whenever lat or lng values changes as they are dependencies and use above code. I believe you can understand the code in useEffect hook. If not, reply to me, I'll explain
  3. Add a reference in the MapContainer Component using ref tag and done.