Reputation: 33
I'm working with mapbox-gl-js in a React (Next.js) project and I'm having trouble figuring out how to dynamically style markers differently when they are clicked. Specifically, I would like to enlarge the active marker and bring it to the front.
I followed the [official store locator example], which works very well, but does not contain any dynamic marker styling (https://docs.mapbox.com/help/tutorials/building-a-store-locator/).
I am able to render custom markers by using ReactDOM.createRoot, but I'm not sure how to update the marker styling based on the active marker's id stored in my component state. I've tried searching the Mapbox GL JS docs and various tutorials but haven't found a clear solution for dynamically updating marker styles onClick in a React context.
How can I dynamically restyle the active marker (e.g. increasing size and z-index) when it is clicked? Is there a recommended way to accomplish this with Mapbox GL JS markers in a React/Next.js environment?
Any guidance or code samples would be greatly appreciated. Let me know if you need any additional details about my setup. Thanks in advance!
Here's a snippet of my code based on the aforementioned example. This does its job well, but I'm it's not clear to me where the dynamic map styling would occur.
jsx
geojson.features.forEach((marker) => {
const customMarker = <CustomMarker />;
const el = document.createElement('div');
const root = ReactDOM.createRoot(el);
root.render(customMarker);
el.id = `marker-${marker.properties.id}`;
el.className = 'marker';
new mapboxgl.Marker(el, { anchor: 'bottom' })
.setLngLat(marker.geometry.coordinates as LngLatLike)
.addTo(map);
el.addEventListener('click', () => {
centerMarker(marker);
setActiveMarkerId(marker.properties.id);
// Any way to rerender the active marker (i.e. modifying z-index and size)?
});
el.addEventListener('mouseenter', () => {
createPopUp(marker);
});
el.addEventListener('mouseleave', () => {
removePopUps();
});
});
Upvotes: 0
Views: 345
Reputation: 1
The docs say you need to use Layers or something to dynamically style the markers, but I found you can easily achieve the same effect by just targeting the container element and using css classes. So just create classes for the effects you want and activate them based on a class on the container element, and in your onClick toggle classes on the container.
Upvotes: 0