zimnykisiel
zimnykisiel

Reputation: 98

Why map resize is not working when layout changes?

I am trying to implement layout with map and sidebar. Everything seems to be working fine until I collapse sidebar (change its width to smaller value). After the sidebar is collapsed, the map should be extended to fill the rest with the space, but on the right side there is a blank space with the width of the collapsed sidebar.

Link to the demo

Link to sandbox

I was trying to use resize function when calling toggle sidebar method, but transition of the sidebar takes 0.3s, so resize will be called before animation is complete and blank space still be visible. I was also trying to set timeout for the duration of the animation and then calling resize, but blank space was still visible for a split second and map resize wasn't smooth.

I noticed that mapbox is tracking resize of the window, but not resize of the parent element.

function Root() {
  const [expanded, setExpanded] = React.useState(true);
  const toggle = () => {
    setExpanded((prev) => !prev);
  };
  return (
    <div style={{ display: "flex" }}>
      <div style={{ width: expanded ? 700 : 100, background: "red" }}>
        <button onClick={toggle}>Toggle</button>
      </div>
      <Map
        initialViewState={{
          latitude: 37.8,
          longitude: -122.4,
          zoom: 14,
        }}
        style={{ width: "100%", height: "100vh" }}
        mapStyle="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
      >
        <Marker longitude={-122.4} latitude={37.8} color="red" />
      </Map>
    </div>
  );
}

Upvotes: 0

Views: 41

Answers (1)

Rien de jong
Rien de jong

Reputation: 11

You're looking for the setTimeout() function from the React library, here's some information from the docs itself: https://react.dev/learn/synchronizing-with-effects#putting-it-all-together

Your solution would be adding a slight delay to the mapbox resize with the usage of the setTimeout check the sandbox here:

https://codesandbox.io/p/sandbox/epic-napier-2lpf29

Goodluck!

Upvotes: 1

Related Questions