Closed YoniH closed 5 years ago
I copied and modified some code I found on the internet. I'm not sure if this solution is "good", but at least it's working: https://stackoverflow.com/a/54504646/1321564
you can also use L.divIcon and then reactDOM.renderToString to generate its html
I can render custom React component markers like this: `icon={L.divIcon({ className: "custom icon", html: ReactDOMServer.renderToString(
)
})}`
But there is one issue - event handlers (e.g. onClick) won't work, see: https://stackoverflow.com/questions/36323336/onclick-handler-not-registering-with-reactdomserver-rendertostring
I can render custom React component markers like this:
icon={L.divIcon({ className: "custom icon", html: ReactDOMServer.renderToString( <MyComponent/> ) })}
But there is one issue - event handlers (e.g. onClick) won't work, see: https://stackoverflow.com/questions/36323336/onclick-handler-not-registering-with-reactdomserver-rendertostring
You could use the eventHandlers
prop from the react-leaflet
documentation here https://react-leaflet.js.org/docs/api-components/.
It worked for me.
<Marker
position={[50.5, 30.5]}
eventHandlers={{
click: () => {
console.log('marker clicked')
},
}}
/>
Fyi, I found a great library to use React component as the Marker icon here https://www.npmjs.com/package/react-leaflet-enhanced-marker
The renderToString
trick, which the react-leaflet-enhanced-marker also uses will only get you so far. Those components will just be static and can't have event handlers or state of their own.
I have posted an answer over on SO which uses portals to achieve a "true" component-as-marker setup.
Ive now formalised this as a proper solution https://github.com/adamscybot/react-leaflet-component-marker. Fully interactive component markers.
I am using svg custom markers. I want the fill color of the marker to change dynamically based on a prop. So instead of setting an svg file as the icon, I want to set a React component that gets a color prop, and renders an svg tag, using that prop for fill color. Is that possible?