Combining the answers above, you can use a custom hook to get the size of your container
import { useState, useEffect } from "react"
export default function useSize(ref) {
const [size, setSize] = useState({})
useEffect(() => {
if (ref.current == null) return
const observer = new ResizeObserver(([entry]) => setSize(entry.contentRect))
observer.observe(ref.current)
return () => observer.disconnect()
}, [])
return size
}
Create another component to fetch new tiles every time the map is resized
import { useMap } from "react-leaflet";
const ResizeMap = ({ containerRef }) => {
const map = useMap();
const { width, height } = useSize(containerRef);
useEffect(() => {
if (map) {
setTimeout(() => {
map.invalidateSize();
}, 100);
}
}, [height, width]);
return null;
};
Then in your map you can assign a ref to your container and pass that ref to your ResizeMap component
const containerRef = useRef(null)
<div ref={containerRef} className="container">
<MapContainer
{...props}
style={{ width: "100%", height: "100%" }}
>
<ResizeMap containerRef = {containerRef} />
...
</MapContainer >
<div>
This way you can handle the size of your map with any styles defined in the .container class