Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
FleetAdmiralJakob opened this issue Oct 15, 2023 · 1 comment
Open

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

FleetAdmiralJakob opened this issue Oct 15, 2023 · 1 comment

Comments

@FleetAdmiralJakob
Copy link

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
Copy link

KarthikYerra1 commented Apr 13, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants