Design comparison
Solution retrospective
When an IP address is searched, the tiles are not updating on their own but the marker is updating just fine. I need some help regarding this.
Community feedback
- @CarlHummPosted 10 months ago
Hi there
I saw your comment on discord and have taken a brief look for you. So far I can see that:
- You enter your IP Address
- You click submit
- Coordinates is updated and passed to your Map component
- Map does not move
The reason the map does not move is due to Immutability of MapContainer
So once our new coordinates reach our Map component, we cannot use the MapContainer props directly to set the view (like we did with center on initialization).
Instead we must use a custom component and the useMap() hook. The useMap() hook provides our custom component with an instance of our Map, and exposes some helpful functions which allow us to change the view for our map. The useMap() hook knows which map instance to use by default based on which MapContainer we have nested our custom child component within.
Here is a simple example based on your Map component
import "leaflet/dist/leaflet.css"; import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet"; import { Icon } from "leaflet"; import CustomIcon from "../assets/icon-location.svg"; function UpdateMap({latitude, longitude}) { const map = useMap(); map.setView([latitude, longitude], map.getZoom()); return null } const Map = ({ lat, lng }) => { const customIcon = new Icon({ iconUrl: CustomIcon, iconSize: [30], }); return ( <MapContainer id="map" center={[lat, lng]} zoom={13} scrollWheelZoom={false} > <TileLayer attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <Marker position={[lat, lng]} icon={customIcon}> <Popup> <b>Latitude: </b> {lat} <b>Longitude: </b> {lng} </Popup> </Marker> <UpdateMap latitude={lat} longitude={lng} /> </MapContainer> ); }; export default Map;
Also, I see in App.js you have done this
<Map lat={coords[0] || 51.505} lng={coords[1] || -0.09} />
Instead of providing an expression with the OR operator you could take those default values (51.505, -0.09) and use them as initial values for your useState. Like this:
const [coords, setCoords] = useState([51.505, -0.09]);
Hope this helps! I'll be happy to clear up any questions if you have any.
Marked as helpful1@ayushknathPosted 10 months ago@CarlHumm Thanks for the solution. And yes I'll update useState initialisation as you've mentioned.
1
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord