react-leaflet icon indicating copy to clipboard operation
react-leaflet copied to clipboard

looking for help using contexts to get the Map instance

Open Jonahss opened this issue 10 years ago • 7 comments

Hello, thanks for the great module, with tons of excellent documentation. I don't have much react experience, but the docs were enough to get me completely set up.

You helpfully explained that React Contexts can be used to get the Leaflet.Map instance, but I'm having trouble wrapping my brain around the concept. Could you help me with an example of how to get the map property so that I can call Leaflet methods like panTo()?

Are the special context properties only accessible from children of the <Map> component, or am I able to get a reference to map from the parent of a <Map> component?

Simplified example of what I'm trying to do: https://jsfiddle.net/rx5pd4pt/

Jonahss avatar Nov 18 '16 18:11 Jonahss

As I understand, it's all about ref in react. So, you can have a component like this. In componentDidUpdate() method, leaflet instance is taken for invalidateSize() operation.

class MapPreview extends Component{
...
render() {
        return (
            <Map  key="maymap" 
                   ref="map"
            >
...
</Map>)}
componentDidUpdate(){
        var map = this.refs.map.leafletElement;
        map.invalidateSize()
    }
}

lkolek avatar Nov 18 '16 19:11 lkolek

Hi, If you want to access the Map instance created by Leaflet, you can do it using the leafletElement of the Map component after the componentDidMount() handled is triggered, ex:

class MyMap extends Component {
  componentDidMount () {
    const map = this.refs.map.leafletElement
    map.panTo(...)
  }

  render () {
    return <Map ref='map' ...>...</Map>
  }
}

PaulLeCam avatar Nov 19 '16 11:11 PaulLeCam

Thank you :)

Jonahss avatar Nov 22 '16 19:11 Jonahss

Ah, this helped me. The documentation says to use context, but context is only available for child components!

louh avatar Nov 23 '16 18:11 louh

copy that

taozhi8833998 avatar Mar 13 '17 11:03 taozhi8833998

Please where in the documentation is it said to use context because i cant seem to find it

felixsonyusuftosin avatar Oct 12 '17 16:10 felixsonyusuftosin

@PaulLeCam great! I tried your solution and It helped me

Mloweedgar avatar Oct 05 '18 12:10 Mloweedgar