3

I'm using react to render a leaflet map. Since I can't get the map object instance from the DOM, how can I retrieve the instance from components inside different routes ?

App.js

const Main = React.createClass({

  componentDidMount: function() {
    map = L.map('map', {}).setView([45, 0], min_zoom);
    let layer = L.tileLayer('https://api....}', { }).addTo(map);
  },

  render() {
    return (
      <div id='map'>
        <div id='container'>
          {this.props.children}
        </div>
      </div>
    );
  }
});

import Travel from './routes/Travel';

render((
  <Router history={history}>
    <Route path="/" component={Main}>
      <Route path="/travel/:name" component={Travel}/>
    </Route>
  </Router>
), document.getElementById('app'));

Routes/Travel.js

const Travel = React.createClass({

  componentDidMount: function() {

    GET THE MAP INSTANCE HERE // UNDEFINED
  },


  render() {
      return (
        <div id='storyBox'>
        </div>
      );
  });

  module.exports = Travel;

Many thanks

1 Answer 1

1

You could pass the map instance in Main to the child component as a property:

const Main = React.createClass({

  componentDidMount: function() {
    this.map = L.map('map', {}).setView([45, 0], min_zoom);
    let layer = L.tileLayer('https://api....}', { }).addTo(map);
  },

  render() {
    return (
      <div id='map'>
        <div id='container'>
          {React.cloneElement(this.props.children, {map: this.map})}
        </div>
      </div>
    );
  }
});

Routes/Travel.js

const Travel = React.createClass({

  componentDidMount: function() {
    if (this.props.map) {
       // whatever
    }
  },
  render() {
      if (!this.props.map) return null;

      return (
        <div id='storyBox'>
        </div>
      );
  });

  module.exports = Travel;
1
  • 1
    You made my day Jack. Thx.
    – Yoann
    Commented Dec 10, 2015 at 9:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.