PaulLeCam / react-leaflet

React components for Leaflet maps
https://react-leaflet.js.org
Other
5.16k stars 887 forks source link

Is it possible to have a React component as custom marker icon? #563

Closed YoniH closed 5 years ago

YoniH commented 5 years ago

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?

benneq commented 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

wmertens commented 5 years ago

you can also use L.divIcon and then reactDOM.renderToString to generate its html

longsangstan commented 4 years ago

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

jaballogian commented 2 years ago

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

adamscybot commented 9 months ago

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.

adamscybot commented 3 months ago

Ive now formalised this as a proper solution https://github.com/adamscybot/react-leaflet-component-marker. Fully interactive component markers.