slutske22 / react-esri-leaflet

react components for esri-leaflet
https://codesandbox.io/s/github/slutske22/react-esri-leaflet/tree/master/examples/ts
MIT License
37 stars 5 forks source link

Can't change basemap layer #16

Closed bobmoretti closed 2 years ago

bobmoretti commented 2 years ago

I have an application with components in the following basic structure:

<MapContainer>
  <BasemapLayer name={mapType} />
</MapContainer>

In this case, mapType is created via useState().

I want to be able to change mapType (e.g., via a UI control) and have the basemap layer re-draw with the new layer.

However, when I try this, the basemap layer never updates, staying the same as it was when it started.

I made a minimal example of the problem here: https://codesandbox.io/s/prod-shadow-xokzy3?file=/src/App.tsx

I am very unfamiliar with React, so this is probably user error, but I'm not sure the best way to work around this issue.

slutske22 commented 2 years ago

As far as I can tell, there doesn't exist such a method even on the underlying L.esri.BasemapLayer to change the type of basemap after it has been defined. So, like many props in react-leaflet, the name prop is immutable, meaning changing it after it has mounted will not affect anything.

To do what you're trying to do, the stupidest easiest way to do it is to simply assign a key to the <BasemapLayer />, which will tell react to force-rerender the layer when mapType changes.

Working example

Hope that helps!

bobmoretti commented 2 years ago

Great, thanks so much for looking into it and providing an example!