Reputation: 71
Hey guys so basically my website is currently looking like this. My aim is to collapse the left sidebar when the user clicks the arrow on top right which turns the smallMapSidebar state true when clicked.
However when the width of the sidebar changes the map does not cover the new space and looks like this
This is my current code of my map component.
import React, { useState, useEffect, useRef } from "react";
// map imports
import Map from "react-map-gl";
import MapboxGl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
// styling imports
import "../../styles/map/MapComponent.css";
// added the following 6 lines.
import mapboxgl from "mapbox-gl";
const TOKEN = "map-token";
function MapComponent({ smallMapSidebar }) {
const mapRef = useRef(null);
const resizeMap = MapboxGl.Map.prototype;
useEffect(() => {
// console.log(resizeMap);
if (smallMapSidebar === true) {
mapRef.current.resize();
// console.log(mapRef.current);
}
}, [smallMapSidebar, resizeMap]);
return (
<div className="map-container">
<Map
ref={mapRef}
id="map-container"
mapboxAccessToken={TOKEN}
initialViewState={{
longitude: -0.118092,
latitude: 51.509865,
zoom: 10,
}}
style={{
width: "100%",
height: "100%",
}}
mapStyle="mapbox://styles/mapbox/dark-v9"
onClick={(event) => event.target.resize()}
onResize={(event) => {
event.target.resize();
}}
/>
</div>
);
}
export default MapComponent;
I have tried to mock the resize function by reaching the map component with useRef but that did not work.
Is there a way to trigger the .resize function when the smallMapSidebar state turns true.
Thank you for your time
Upvotes: 5
Views: 845
Reputation: 1348
I had the same problem. By searching and trying different methods through the features of the plugin, I did not get anywhere, but I solved the problem in a way that I know is not the best solution.
As we know, states cause the component to be re-rendered. I defined a state that is updated every time the sidebar collapses and finally causes the map component to be re-rendered. This makes the size of the map correct.
This is my init state:
const [reRenderMap, setReRenderMap] = useState(1)
And every time my sidebar collapse or uncollapsed, I set timestap value to the my state:
setReRenderMap(Date.now())
In the end, by using this state as the key of the main component of the map, it can be re-rendered every time it collapses:
<Map
key={reRenderMap} // The state called here
initialViewState={{
// ...
}}
mapStyle="mapbox://..."
mapboxAccessToken='
>
Upvotes: 2