Search code examples
cssreactjsmapboxmaplibre-gl

How to style a map container with CSS using ReactJS


My map is implemented using MapLibre GL, but this issue also happens with Google Maps API or Mapbox GL.

I have the following ReactJS component:

import React, { useRef, useEffect } from "react";
import maplibregl from "maplibre-gl";
import map_style from "./style/style.json";

export default function Map() {
  const mapContainer = useRef(null);
  const map = useRef(null);

  useEffect(() => {
    if (map.current) return; //stops map from intializing more than once
    map.current = new maplibregl.Map({
      container: mapContainer.current,
      style: map_style,
      center: [12, 26],
    });
  });

  return (
      <div
        ref={mapContainer}
        className="my-map"
        style={{ height: 500, width: 500 }}
      />
  );
}

The above code renders the map, but I do not want a fixed height and width. I need to apply different styles depending on parent DOM elements, screen sizes, etc.

Problem is, right now if I assign a width and height in my CSS file, it's not being applied to the map. On the other hand, if I remove or change the syntax of style={{ height: 500, width: 500 }} in my ReactJS component, the map fails to display.

How can I style with CSS in this scenario?


Solution

  • The map library needs to read the container dimensions to compute the inner view.

    As long as you provide explicit size, possibly through className, you should be fine.

    Most mapping libraries also offer some API to request a re-read of the container dimensions, so that the view can be adjusted when the container is revealed or changes size (possibly for responsiveness). In the case of MapLibre GL JS, see resize() map method:

    Resizes the map according to the dimensions of its container element.

    Checks if the map container size changed and updates the map if it has changed. This method must be called after the map's container is resized programmatically or when the map is shown after being initially hidden with CSS.