Search code examples
reactjsreact-routermapboxmapbox-gl-jsmapbox-marker

How to add react-router-link to mapbox marker created with forEach method


I am not that expierienced with mapbox library and I have a question: How do I add router link to each mapbox marker? Because if I use window.location it works, but my map component re-renders every time I click on the marker. Basically, what I want to do is to change window.location to Router-link.

rtdb.ref('/').once('value').then((snapshot) => {
  if (snapshot.exists()) {
    snapshot.val().features.forEach(function (marker) {
      
      new mapboxgl.Marker().setLngLat(marker.geometry.coordinates).addTo(map).getElement().addEventListener('click', () => {
        //<Link to={'/markerinfo/' + marker.properties.docID}/> 
        //window.location=('/markerinfo/'+marker.properties.docID)
      })
    }
    )
  } else console.log("No data available")
}).catch((error) => {
  console.error(error);
});

Solution

  • I think you are looking for "how to programmatically navigate" try using

    import { useHistory } from "react-router-dom";
    function YourComponent(){
      const history = useHistory();
    
    
    }
    

    then in your function

    rtdb.ref('/').once('value').then((snapshot) => {
      if (snapshot.exists()) {
        snapshot.val().features.forEach(function (marker) {
          
          new mapboxgl.Marker().setLngLat(marker.geometry.coordinates).addTo(map).getElement().addEventListener('click', () => {
          
             history.push('/markerinfo/'+marker.properties.docID);
          })
        }
        )
      } else console.log("No data available")
    }).catch((error) => {
      console.error(error);
    });