Mapbox-gl-js: Dynamically changing styles with styled-components causes mapboxgl-map class to disappear.

Created on 10 Jul 2018  路  2Comments  路  Source: mapbox/mapbox-gl-js

This behavior caused me a huge headache, and I've narrowed down the problem. I don't know if this is something for Mapbox to deal with-- perhaps it may make a good caveat in the react + mapbox docs/blog posts.

mapbox-gl-js version:
0.46.0
browser:
chrome

Steps to Trigger Behavior

Using React, styled-components, and mapbox-gl:

  1. Create a map container as a styled-component
  2. The container's style should be determined by incoming props (e.g. width or grid position).
  3. Change the props, and watch everything explode!

Changing the styled-component's props causes new class names to be generated, and the mapboxgl-map class is not recreated. Despite this fact, map.resize() still works as expected, and the ref still exists.

Quick-fix solutions include:

  1. Re-inject the class using the DOM ref (which you already created to inject the map in the first place).
  2. Add mapboxgl-map as a className prop or styled-components attr object.

Link to Demonstration

https://codesandbox.io/s/z64o54w3jp

Expected Behavior

Passing a new prop to a styled-components map container (e.g. width, height), and calling resize(), should work.

Actual Behavior

mapboxgl-map class is destroyed, mapbox is not clever enough to detect the missing class and re-add it. If resize() can detect the new container size and fit appropriately, I would expect it to re-inject the class.

Most helpful comment

Unfortunately we don't have the capacity to debug issues with third-party frameworks like React. I'll reopen the issue if you're able to provide a minimal test case without frameworks that gets to the root of the problem, proving that it's on the GL JS side.

All 2 comments

Unfortunately we don't have the capacity to debug issues with third-party frameworks like React. I'll reopen the issue if you're able to provide a minimal test case without frameworks that gets to the root of the problem, proving that it's on the GL JS side.

For those who are running into this because the map controls (zoom, compass) are going wonky when repositioning the map container using Styled Components, the easiest thing you can do is go for quick solution 2:

Add mapboxgl-map as a className prop or styled-components attr object.

It's a one-line fix and works every time.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yoursweater picture yoursweater  路  3Comments

iamdenny picture iamdenny  路  3Comments

aderaaij picture aderaaij  路  3Comments

shotor picture shotor  路  3Comments

foundryspatial-duncan picture foundryspatial-duncan  路  3Comments