Sokrat Lapa
Sokrat Lapa

Reputation: 21

MapBox can't add react component on markers popup

I have been working on a Real Estate project and I've got stuck on adding a reactcomponent inside a markers popup. The image below shows the example of how the popup should look like: Popup example

This is the code where I am trying to add the popup on the marker:

var card = <Card />
var popup = new mapboxgl.Popup({ offset: 25 })
.setDOMContent(ReactDOM.render(card, document.getElementById('map')))

var marker = new mapboxgl.Marker(el)
.setLngLat(coordinates)
.setPopup(popup)
.addTo(map);
setMarkers(markers => [...markers, marker])

I keep getting the same error:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Please help me!

Upvotes: 2

Views: 1394

Answers (1)

Jun Koyama
Jun Koyama

Reputation: 21

The expected argument type of setDOMContent is Node, but the return type of ReactDOM.render is Component.
https://reactjs.org/docs/react-dom.html#render
https://docs.mapbox.com/mapbox-gl-js/api/markers/#popup#setdomcontent

In React, use React.useRef and .current to refer dom content.
https://reactjs.org/docs/hooks-reference.html#useref

const popupRef = React.useRef(null);
const popup = new mapboxgl.Popup({ offset: 25 })
  .setDOMContent(popupRef.current);

return (
  <>
    <div id="map"></div>
    <div ref={popupRef}>popup</div>
  </>
);

Upvotes: 2

Related Questions