Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference on object instance - React

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

like image 575
Yoann Avatar asked Sep 20 '26 18:09

Yoann


1 Answers

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;
like image 59
Jack Avatar answered Sep 23 '26 08:09

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!