You can get the mapbox-gl map object once the component mounts, then you can work with it directly. Try something like this:

class MapPage extends Component {
      constructor(props) {
        super(props);
         this.state = {
          viewport: {
           latitude: 38.63738602787579,
           longitude: -121.23576311149986,
           zoom: 6.8,
           bearing: 0,
           pitch: 0,
           dragPan: true,
           width: 600, 
           height: 600 
         }
        };
       }
    componentDidMount(){
      const map = this.reactMap.getMap();
      map.on('load', () => {
       //add the GeoJSON layer here
       map.addLayer({...})
      })
    }

    render() {
      const { viewport } = this.state;

      return (
        <ReactMapGL
          ref={(reactMap) => this.reactMap = reactMap} />
          {...viewport}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          onViewportChange={newViewport => {
            this.setState({ viewport: newViewport });
          }}
        />
      );
     }
    }

React Refs: https://reactjs.org/docs/refs-and-the-dom.html

GetMap(): https://uber.github.io/react-map-gl/#/Documentation/api-reference/static-map?section=methods

Answer from Kristofor Carle on Stack Overflow
🌐
React Map GL
visgl.github.io › adding custom data
Adding Custom Data | react-map-gl
import * as React from 'react'; import Map, {Source, Layer} from 'react-map-gl/maplibre'; import type {CircleLayer} from 'react-map-gl/maplibre'; import type {FeatureCollection} from 'geojson'; const geojson: FeatureCollection = { type: 'FeatureCollection', features: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-122.4, 37.8] }, properties: {title: '915 Front Street, San Francisco, California'} } ] }; const layerStyle: CircleLayer = { id: 'point', type: 'circle', paint: { 'circle-radius': 10, 'circle-color': '#007cbf' } }; function App() { return ( <Map initialViewState={{ longitude: -122.45, latitude: 37.78, zoom: 14 }}> <Source id="my-data" type="geojson" data={geojson}> <Layer {...layerStyle} /> </Source> </Map> ); }
🌐
npm
npmjs.com › package › react-map-gl-draw
react-map-gl-draw - npm
October 4, 2022 - data (Feature[]) - the updated list of GeoJSON features. editType (String) - addFeature, addPosition, finishMovePosition · editContext (Array) - list of edit objects, depend on editType, each object may contain featureIndexes, editHandleIndexes, screenCoords, mapCoords. ... { id, // an unique identified generated inside react-map-gl-draw library geometry: { coordinates, // latitude longitude pairs of the geometry points type // geojson type, one of `Point`, `LineString`, or `Polygon` }, properties: { renderType, // Mainly used for styling, one of `Point`, `LineString`, `Polygon`, or `Rectangle`. Different from `geometry.type`. i.e.
      » npm install react-map-gl-draw
    
Published   Oct 04, 2022
Version   1.0.4
Discussions

I am trying to use the react-map-gl geolocation example but .geojson data not willing to load - Stack Overflow
The 'd3-request' module seems to be deprecated, but I can't get it working with 'd3-fetch' instead, as suggested. How do I load .geojson data in react-map-gl? More on stackoverflow.com
🌐 stackoverflow.com
How to edit and interact with existing GeoJSON data with react-map-gl
I'm looking for a way to implement the following use case: I have a react-map-gl map loaded with several layers: Layer 0: A fill-extrusion layer which I'm getting from a Mapbox Studio data source... More on stackoverflow.com
🌐 stackoverflow.com
oop - ReactMapGL add points from geoJSON - Stack Overflow
Yeah I saw your comment via email, maybe an over keen mod decided to delete it, no idea. Text is done as a Symbol layer, the same Symbol layer can be used for both an icon + text, or you could use a circle layer for the icon + symbol layer for the text. docs.mapbox.com/mapbox-gl-js/style-s... More on stackoverflow.com
🌐 stackoverflow.com
reactjs - How to use a local GeoJSON file with Mapbox in React - Stack Overflow
Good day, I am using Mapbox in React to make a map with a polygon layer. The issue is that I have to use a local GeoJSON file for the polygon layer and I cannot use a URL. I have seen some solution... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
10

You can get the mapbox-gl map object once the component mounts, then you can work with it directly. Try something like this:

class MapPage extends Component {
      constructor(props) {
        super(props);
         this.state = {
          viewport: {
           latitude: 38.63738602787579,
           longitude: -121.23576311149986,
           zoom: 6.8,
           bearing: 0,
           pitch: 0,
           dragPan: true,
           width: 600, 
           height: 600 
         }
        };
       }
    componentDidMount(){
      const map = this.reactMap.getMap();
      map.on('load', () => {
       //add the GeoJSON layer here
       map.addLayer({...})
      })
    }

    render() {
      const { viewport } = this.state;

      return (
        <ReactMapGL
          ref={(reactMap) => this.reactMap = reactMap} />
          {...viewport}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          onViewportChange={newViewport => {
            this.setState({ viewport: newViewport });
          }}
        />
      );
     }
    }

React Refs: https://reactjs.org/docs/refs-and-the-dom.html

GetMap(): https://uber.github.io/react-map-gl/#/Documentation/api-reference/static-map?section=methods

2 of 3
5

Applicable for those who are using react-map-gl Version 5.0 onwards

As of October 2019, react-map-gl supports Layer and Source components, which is meant to allow developers to render Mapbox layers on the Mapbox canvas without the need to call getMap() to expose the underlying native Mapbox API.

You may refer to the original Mapbox Source and Layer documentations for the full specifications for the valid values for the Layer and Source props.

This is how the Source and Layer components can be used together with the code you have provided to generatea GeoJSON line on your map.

class MapPage extends Component {
  constructor(props) {
    super(props);
     this.state = {
      viewport: {
       latitude: 38.63738602787579,
       longitude: -121.23576311149986,
       zoom: 6.8,
       bearing: 0,
       pitch: 0,
       dragPan: true,
       width: 600, 
       height: 600 
     }
    };
   }

render() {
  const { viewport } = this.state;

  return (
    <ReactMapGL
      {...viewport}
      mapboxApiAccessToken={MAPBOX_TOKEN}
      onViewportChange={newViewport => {
        this.setState({ viewport: newViewport });
      }}
    >
      <Source id='polylineLayer' type='geojson' data={polylineGeoJSON}>
        <Layer
          id='lineLayer'
          type='line'
          source='my-data'
          layout={{
           'line-join': 'round',
           'line-cap': 'round',
          }}
          paint={{
           'line-color': 'rgba(3, 170, 238, 0.5)',
            'line-width': 5,
          }}
        />
      </Source>
    </ReactMapGL>
  );
 }
}
🌐
React Map GL
visgl.github.io › react-map-gl › examples
react-map-gl
Mapbox · Clusters · Markers, Popups and Controls · Custom Cursor · Draggable Marker · Draw Polygon · Highlight By Filter · Geocoder · GeoJSON Animation · GeoJSON · Heatmap · Limit Map Interaction · Dynamic Styling · Side by Side · Terrain · Camera Transition ·
🌐
Ojlamb
ojlamb.com › React-Map-GL
Working with react-map-gl - Owen Lamb
A couple of things to note here, is the onLoad function. When the map loads for the first time, it will kick off the getMapLayers function, generate the new style and on the next render it the map will consume the new mapStyle with you custom geoJson. Sweet! Working with react-map-gl was enjoyable.
🌐
GitHub
github.com › urbica › react-map-gl
GitHub - urbica/react-map-gl: React Component Library for Mapbox GL JS · GitHub
import React from 'react'; import ... }} /> </MapGL>; To draw a GeoJSON on a map, add Source with the type property set to geojson and data property set to a URL or inline GeoJSON....
Starred by 424 users
Forked by 49 users
Languages   JavaScript
🌐
Medium
edisondevadoss.medium.com › map-using-react-map-gl-511f08f0b330
Map using React map gl .. Friends, in this article, I will… | by Edison Devadoss | Medium
December 12, 2019 - In that geojson it has the geolocation information of four southern states of India. ... import React, { Component } from 'react'; import { render } from 'react-dom'; import MapGL, { Source, Layer } from 'react-map-gl'; import ControlPanel from './control-panel'; import { dataLayer } from './map-style.js'; import { updatePercentiles } from './utils'; import LegenPanel from './legend-panel';const MAPBOX_TOKEN = '';export default class App extends Component { constructor(props) { super(props) this.state = { year: 2015, week: 1, month: 1, data: null, hoveredFeature: null, viewport: { width: '100v
Top answer
1 of 1
1

To load GeoJSON file via d3-fetch library:

1) import json function: import { json } from 'd3-fetch'

2) now file content could be downloaded like this:

json("data/us-income.geojson")
.then((data) => {
    //...
});

Here is an official example adapted for react-map-gl library:

const MAPBOX_TOKEN =
  "--YOUR_KEY-GOES-HERE--"; // 
const SOURCE_ID = "national-park";

class Map extends Component {
  constructor(props) {
    super(props);

    this.state = {
      viewport: {
        latitude: 40.492392,
        longitude: -121.403732,
        zoom: 11
      }
    };

    this.mapRef = React.createRef();
    this.handleMapLoaded = this.handleMapLoaded.bind(this);
    this.handleViewportChange = this.handleViewportChange.bind(this);
  }

  handleViewportChange(viewport) {
    this.setState({ viewport });
  }


  handleMapLoaded() {
    const map = this.mapRef.current.getMap();

    json("data/national-park.json")
    .then((data) => {
      this.initMapData(map, data);
    });

  }

  render() {
    const { viewport } = this.state;

    return (
      <div style={{ height: "100%" }}>
        <MapGL
          ref={this.mapRef}
          onLoad={this.handleMapLoaded}
          mapStyle="mapbox://styles/mapbox/outdoors-v11"
          width="100%"
          height="480px"
          {...viewport}
          onViewportChange={this.handleViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
        />
      </div>
    );
  }

  initMapData(map, data) {
    map.addSource(SOURCE_ID, data);
    map.addLayer({
      id: "park-boundary",
      type: "fill",
      source: "national-park",
      paint: {
        "fill-color": "#888888",
        "fill-opacity": 0.4
      },
      filter: ["==", "$type", "Polygon"]
    });

    map.addLayer({
      id: "park-volcanoes",
      type: "circle",
      source: "national-park",
      paint: {
        "circle-radius": 6,
        "circle-color": "#B42222"
      },
      filter: ["==", "$type", "Point"]
    });
  }
}
Find elsewhere
Top answer
1 of 1
2

Here's a solution with react-map-gl and mapbox-gl-draw. At this point, nebula.gl and the forked successor @deck.gl-community/editable-layers should not be used as they are both unmaintained.

We'll use react-map-gl's draw-polygon example:

https://github.com/visgl/react-map-gl/tree/master/examples/mapbox/draw-polygon

Unfortunately, that example provides no means to load existing geometries that can then be modified or added to.

The most important changes to be made are in DrawControl. We make theMapboxDraw object accessible from up in the component tree with use of forwardRef() and useImperativeHandle()

import { forwardRef, useImperativeHandle } from 'react';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
import { useControl } from 'react-map-gl';

const DrawControl = forwardRef((props, ref) => {
  const drawRef = useControl(
    () => new MapboxDraw(props),
    ({ map }) => {
      map.on('draw.create', props.onCreate);
      map.on('draw.update', props.onUpdate);
      map.on('draw.delete', props.onDelete);
      map.on('draw.modechange', (evt) => {
        console.log('on', evt.mode);
      });
    },
    ({ map }) => {
      map.off('draw.create', props.onCreate);
      map.off('draw.update', props.onUpdate);
      map.off('draw.delete', props.onDelete);
      map.off('draw.modechange', (evt) => {
        console.log('off', evt.mode);
      });
    },
    {
      position: props.position,
    },
  );

  useImperativeHandle(ref, () => drawRef, [drawRef]);

  return null;
});

export default DrawControl;

This makes the MapboxDraw object available for use up in the component tree as drawRef.current. In my higher up component below, I create the drawRef, pass said drawRef to DrawControl and then use useEffect() to add my feature collection once the reference is available

const EditableMap = (props) => {
  const drawRef = useRef(null);

  const myFeatureCollection = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        geometry: // geometry
      }
    ],
  }

  useEffect(
    () => {
      drawRef.current.add(myFeatureCollection});
    },
    [drawRef.current]
  );

  return (
    <Map
      mapboxAccessToken={REACT_APP_MAPBOX_ACCESS_TOKEN}
      initialViewState={{ ...DEFAULT_VIEWPORT, ...initialViewState }}
      style={style}
      mapStyle={mapStyle}
    >
      <DrawControl
        ref={drawRef}
        position='top-left'
        displayControlsDefault={false}
        controls={{
          polygon: true,
          trash: true,
        }}
        defaultMode={SIMPLE_SELECT_MODE}
        onCreate={onDrawUpdate}
        onUpdate={onDrawUpdate}
        onDelete={onDrawDelete}
        styles={MAPBOX_DRAW_STYLES}
      />
    </Map>
  );
};
🌐
Retz
retz.dev › blog › display-map-data-with-react-and-mapbox
Display Map Data with React and Mapbox - Blog | retzdev
June 16, 2021 - Regardless, we have to take our Sanity geopoint data and transform it into GeoJSON. Then add something components, provided by react-map-gl.
🌐
Nebula
nebula.gl › docs › api-reference › react-map-gl-draw › react-map-gl-draw
React Map GL Draw
data (Feature[]) - the updated list of GeoJSON features. editType (String) - addFeature, addPosition, finishMovePosition · editContext (Array) - list of edit objects, depend on editType, each object may contain featureIndexes, editHandleIndexes, screenCoords, mapCoords. ... { id, // an unique identified generated inside react-map-gl-draw library geometry: { coordinates, // latitude longitude pairs of the geometry points type // geojson type, one of `Point`, `LineString`, or `Polygon` }, properties: { renderType, // Mainly used for styling, one of `Point`, `LineString`, `Polygon`, or `Rectangle`. Different from `geometry.type`. i.e.
🌐
GitHub
github.com › urbica › react-map-gl › blob › main › README.md
react-map-gl/README.md at main · urbica/react-map-gl
import React from 'react'; import ... }} /> </MapGL>; To draw a GeoJSON on a map, add Source with the type property set to geojson and data property set to a URL or inline GeoJSON....
Author   urbica
🌐
GitHub
github.com › alex3165 › react-mapbox-gl › blob › master › example › src › demos › geojsonLayer.tsx
react-mapbox-gl/example/src/demos/geojsonLayer.tsx at master · alex3165/react-mapbox-gl
import ReactMapboxGl, { GeoJSONLayer } from '../../../'; import * as MapboxGL from 'mapbox-gl'; · // tslint:disable-next-line:no-var-requires · const { token, styles } = require('./config.json'); // tslint:disable-next-line:no-var-requires · const geojson = require('./geojson.json'); ·
Author   alex3165
🌐
GitHub
github.com › damminhtien › react-map-gl-example › blob › master › node_modules › geojson-vt › README.md
react-map-gl-example/node_modules/geojson-vt/README.md at master · damminhtien/react-map-gl-example
A highly efficient JavaScript library for slicing GeoJSON data into vector tiles on the fly, primarily designed to enable rendering and interacting with large geospatial datasets on the browser side (without a server).
Author   damminhtien
🌐
Sparkgeo
sparkgeo.com › home › use flatgeobuf in react-map-gl
Use Flatgeobuf in react-map-gl | Sparkgeo
May 4, 2023 - If you go back to the DemoMap.jsx component, and replace the GeoJSON Source component provided by react-map-gl with this FlatgeobufSource.jsx component, you should see something like the following:
🌐
Medium
medium.com › @lvas248 › implementing-interactive-and-customizable-maps-in-react-509280877905
Implementing Interactive and Customizable Maps in React | by Luis Vasquez | Medium
May 31, 2023 - FetchFinder NYC uses GeoJSON data supplied by NYC Opendata website to plot out polygons that outline and fill each dog park: ... To programmatically change the map’s view, you can utilize Mapbox’s built-in methods. First, create a reference to the map using the useRef hook: import React, { useRef } from 'react'; function MapComponent() { const mapRef = useRef(null); // ...
🌐
Medium
medium.com › swlh › intro-to-react-mapbox-gl-js-b163aef4d0bd
Intro to React MapBox GL JS. Displaying Polygons | by Dallas Bille | The Startup | Medium
November 10, 2019 - Intro to React MapBox GL JS Displaying Polygons It’s good to be back! Back with another React MapBox article. It has been way too long and I have been insanely busy, so hopefully I can help some …