Reputation: 71
I have to get the address I want to set as the leaflet position through redux. Problem is, when I do that, the map renders like this.
import React, {useEffect} from "react";
import { Container } from "react-bootstrap";
import { fetchOrgData } from "../../features/about/aboutReducer";
import { useDispatch, useSelector } from 'react-redux';
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet'
import 'leaflet/dist/leaflet.css';
const ContactForm = () => {
const dispatch = useDispatch();
const { orgData } = useSelector(state => state.about);
const position = orgData.address;
console.log(position)
console.log(position)
returns [-34.55881726737178, -58.47476996280374] just so you know that state is well called.
useEffect(() => {
dispatch(fetchOrgData());
}, [dispatch]);
return (
<Container
className="d-flex flex-column justify-content-center text-center p-3"
>
<h1>Contacto</h1>
<MapContainer
center={position}
zoom={13}
scrollWheelZoom={false}
style={{ height: "450px", width: "100%" }}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={position}>
</Marker>
</MapContainer>
</Container>
);
};
However, if I hard-code the "position" value to the leaflet prop, the map renders correctly.
<MapContainer
center={[-34.55881726737178, -58.47476996280374]}
zoom={13}
scrollWheelZoom={false}
style={{ height: "450px", width: "100%" }}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[-34.55881726737178, -58.47476996280374]}>
</Marker>
</MapContainer>
This probably has to do with the "orgData" state value not being called soon enough for the map to render correctly with its value. So, how should I proceed to fix this?
Upvotes: 0
Views: 359
Reputation: 1455
You will want to create a ref for the map
const mapRef = useRef();
<Map ref={mapRef}/>
Then access the underlying leaflet map to setView
or flyTo
when the redux selector updates
useEffect(() => {
const zoomLevel = 5;
mapRef.current.leafletElement.flyTo(orgData.address, zoomLevel);
}, [orgData.address]);
Upvotes: 1