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!

1

2 Answers

I had the same problem while following the tutorial. I think it has to do with the updated way React deals with Refs ().

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"/>

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like