While using react-leaflet to create a map, I would like the map component to take over all the available space after header and footer. The code seems to work. However, when the resize handler is triggered, the map component size didn't change. Any suggested fixes?
CodeSandbox link at the bottom.
import React, { useState, useEffect, useRef } from "react";
import { MapContainer, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
const MyMap = () => {
const mapRef = useRef(null);
const [windowHeight, setWindowHeight] = useState(150);
const [loading, setLoading] = useState(true);
useEffect(() => {
const handleResize = () => {
const headerHeight = document.querySelector("header").offsetHeight;
const footerHeight = document.querySelector("footer").offsetHeight;
console.log(
window.innerHeight,
headerHeight,
document.querySelector("header"),
footerHeight
);
setWindowHeight(window.innerHeight - headerHeight - footerHeight - 16);
if (mapRef) {
console.log("map exist", windowHeight, mapRef.current);
}
setLoading(false);
};
window.setTimeout(handleResize, 1000);
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<header>
<h1>HEADER</h1>
</header>
{loading && <div>loading...</div>}
<main style={{ flex: "1 1 auto" }}>
{!loading && (
<MapContainer
center={[51.505, -0.09]}
zoom={13}
style={{ height: `${windowHeight}px` }}
ref={mapRef}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
</MapContainer>
)}
</main>
<footer>
<h1>Footer</h1>
</footer>
</div>
);
};
export default MyMap;
https://codesandbox.io/embed/lknkgg?view=editor+%2B+preview&module=%2Fsrc%2FMyApp.js