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...
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!
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.