Good way to combine React and Leaflet

soueuls picture soueuls · Nov 5, 2014 · Viewed 20.1k times · Source

I am working on a project to combine React and Leaflet, but I must say I am having some hard time with the semantics.

As most of the stuff is managed by Leaflet directly, I don't know if it would make sense to add the Leaflet map instance as state in the React Component or not.

Same problem when it comes to creating markers with Leaflet, as it does not return anything, I don't have anything to render really. The logic itself seems blurry to me.

Here is what I started to make. It's working but I feel like I'm writing bad code and missing the concept.

/** @jsx React.DOM */

/* DOING ALL THE REQUIRE */
var Utils = require('../core/utils.js');

var Livemap = React.createClass({
    uid: function() {
        var uid = 0;
        return function(){
            return uid++;
        };
    },
    getInitialState: function() {
        return {
            uid: this.uid()
        }
    },
    componentDidMount: function() {
        var map = L.map('map-' + this.state.uid, {
            minZoom: 2,
            maxZoom: 20,
            layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '&copy; <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.fitWorld();
        return this.setState({
            map: map
        });
    },
    render: function() {
        return (
            <div className='map' id={'map-'+this.state.uid}></div>
        );
    }
});

(function(){
    Utils.documentReady(function(){
        React.render(
            <Livemap />,
            document.body
        )
    });
})();

So my questions are:

  • Does this sample seem legit?
  • How would you approach the logic of adding markers and managing their events?

Answer

Ross Allen picture Ross Allen · Nov 5, 2014
  • 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 on state. Only store data in state 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: '&copy; <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>
        );
    }

}