Terence Devine
Terence Devine

Reputation: 125

Use MapBox GL JS with React - Error: Invalid type: ‘container’ must be a String or HTMLElement

I am currently adding MapBox to a React project, and was using this tutorial as a guide.

When I add the ref attribute to the map div, I'm get the following error (as have others)

“Error: Invalid type: ‘container’ must be a String or HTMLElement.”

I reached out to MapBox support last week but haven't heard back from them, so any helpful insight would be greatly appreciated. Thanks!

Upvotes: 2

Views: 5918

Answers (3)

user21455096
user21455096

Reputation: 11

In your useEffect, make sure that your mapContainer.current is not null with this : if (!mapContainer.current) return;

Upvotes: 1

jackowsky
jackowsky

Reputation: 57

For me solutions was to set class of div which I want to contain map and then in componentDidMount() referenced through querySelecter instead of createRef. And it works in Gatsby so far.

Upvotes: 0

BurstWizard
BurstWizard

Reputation: 78

I had the same problem while following the tutorial. I think it has to do with the updated way React deals with Refs (https://reactjs.org/docs/refs-and-the-dom.html).

Create the ref within the constructor using :

this.mapContainer = React.createRef();

And then access the ref when defining the map using:

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

Finally,

<div ref = {this.mapContainer} className = "mapContainer"/>

Upvotes: 4

Related Questions