Good way to combine React and Leaflet
- You don't need to manage uniqueness, i.e. "UID", yourself. Instead, you can use
getDOMNode
to access the component's real node. Leaflet's API supports either a string selector or an HTMLElement instance. - Leaflet is managing rendering, so the
map
should not live onstate
. Only store data instate
that affects React's rendering of the DOM element.
Beyond those two points, use the Leaflet API normally and tie callbacks from your React component to the Leaflet map as you like. React is simply a wrapper at this point.
import React from 'react';import ReactDOM from 'react-dom';class Livemap extends React.Component { componentDidMount() { var map = this.map = L.map(ReactDOM.findDOMNode(this), { minZoom: 2, maxZoom: 20, layers: [ L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'}) ], attributionControl: false, }); map.on('click', this.onMapClick); map.fitWorld(); } componentWillUnmount() { this.map.off('click', this.onMapClick); this.map = null; } onMapClick = () => { // Do some wonderful map things... } render() { return ( <div className='map'></div> ); }}
As an additional, less-detailed answer, PaulLeCam's react-leaflet component seems popular. Haven't used it yet but it looks promising:
https://github.com/PaulLeCam/react-leaflet
UPDATE: It's solid. Haven't used many of the features yet but the codebase is well-written and easy to follow and extend, and what I've used works great out of the box.