Skip to content Skip to sidebar Skip to footer

React And Leaflet

I'm trying to use Leaflet in my React App. I'm running into an issue. Leaflet.js requires the div component to pre-exist when initiating the map. React doesn't 'create' the div unt

Solution 1:

You can initialize map inside componentDidMount

classMapboxextendsReact.Component {
  componentDidMount() {
    this.map();
  }

  map() {
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
  }

  render() {
    return<divid="map">xx</div>  
  }
}

Example

Solution 2:

The other answers are great if you're using class components. If you have to use it with functional components (using Hooks) than you might need to code useRef.

functionMap({}) {
  // define the ref hereconst mapRef = useRef(null);

  useEffect( () => {
// set the initialized map to the ref
    mapRef.current = L.map('map').setView([51.505, 3], 13);
    
    }, []);

// pass it in the required div nodereturn (
    <divref={mapRef}id="map"className="p-2"></div>
  );

}

In this way the map will be initialized after the DOM node is rendered.

Reference: React hooks.

Solution 3:

Since react 16.3 there is a new method for creating references easily.

note:the references can be stored in constructor as the refernces can be created prior to the jsx div is created.

classMapextendsReact.Component {


  componentDidMount() {
   this.map = React.createRef();
   var map = L.map(this.map).setView([51.505, -0.09], 13);
  }

  render() {
    return<divref={this.map}></div>
  }
}

Solution 4:

Use "refs". Refs is used to return a reference to the element. docs here

classMapextendsReact.Component {

  componentDidMount() {
    const node = this.node;
    var map = var map = L.map(node).setView([51.505, -0.09], 13);
  }

  render() {
    return<divref={(node) => { this.node = node }}></div>
  }
}

Post a Comment for "React And Leaflet"