PaulLeCam / react-leaflet

React components for Leaflet maps
https://react-leaflet.js.org
Other
5.14k stars 885 forks source link

InvalidateSize and flyToBounds do not work with ref #480

Closed thijssmudde closed 6 years ago

thijssmudde commented 6 years ago

Expected behavior

Opening and closing interface tab, should invalidate the map size and the polyline should be centered.

Actual behavior

invalidateSize and flyToBounds do not work on the ref object.

Steps to reproduce

Map component has a ref:

ref={(ref) => this.mapRef = ref}

componentWillReceiveProps() {
    const {flyToBounds} = this.props

    console.log(this.mapRef)

    if (flyToBounds) {
      this.mapRef.current.leafletElement.invalidateSize()
      this.mapRef.current.leafletElement.flyToBounds(this.bounds)
    }
 }

Both methods are not available

PaulLeCam commented 6 years ago

From your description it seems you're confusing the usage of React's createRef() and callback ref, please refer to React's docs, it's not an issue with this lib.

thijssmudde commented 6 years ago

Well, can you help understand why the methods invalidateSize() and flyToBounds nor setView are exposed?

Im following this as an example: https://github.com/PaulLeCam/react-leaflet/blob/master/example/components/events.js

It should be possible to access these methods, right?

thijssmudde commented 6 years ago

This worked because I had used StyledComponents which obstructed the use of ref:

<Map
 ref={(ref) => this.mapRef = ref}
...
/>
centerPolyline = () => {
    const {bounds} = this.state
    if (bounds) {
      this
        .mapRef
        .leafletElement
        .invalidateSize()
      this
        .mapRef
        .leafletElement
        .flyToBounds(bounds)
    }
  }