-1

Hi I used the code example in mapbox but it shows nothing (width=0) please guide me, how to implement a map in react js. here is my index.js file:

mapboxgl.accessToken =
  "My token";

class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lng: 5,
      lat: 34,
      zoom: 2
    };
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: this.mapContainer,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [this.state.lng, this.state.lat],
      zoom: this.state.zoom
    });

    map.on("move", () => {
      this.setState({
        lng: map.getCenter().lng.toFixed(4),
        lat: map.getCenter().lat.toFixed(4),
        zoom: map.getZoom().toFixed(2)
      });
    });
  }

1 Answers1

0

You must specify a width and height to your mapbox contianer. Here's how to get it working:

import React from "react";
import "./styles.css";
import mapboxgl from "mapbox-gl";

mapboxgl.accessToken =
  "<token>";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lng: 5,
      lat: 34,
      zoom: 2
    };
  }

  componentDidMount() {
    const map = new mapboxgl.Map({
      container: "map",
      style: "mapbox://styles/mapbox/streets-v11",
      center: [this.state.lng, this.state.lat],
      zoom: this.state.zoom
    });

    map.on("move", () => {
      this.setState({
        lng: map.getCenter().lng.toFixed(4),
        lat: map.getCenter().lat.toFixed(4),
        zoom: map.getZoom().toFixed(2)
      });
    });
  }

  render() {
    return (
      <div
        id="map"
        style={{
          width: "100vw",
          height: "100vh"
        }}
      />
    );
  }
}
Manish
  • 4,903
  • 1
  • 29
  • 39