It sounds like you're trying to create a custom component in react-leaflet v3
. If you're not super familiar with react-leaflet, this might be daunting. The docs on writing a custom component are a little hard to follow. I found this section helpful: Element hook factory
So you need to start with 2 basic functions. One function to create your element, and one to update it. To create it,
// Assuming you've already defined L.TileLayer.WebGis somewhere
// and attached it to the global L
const createWebGisLayer = (props, context) => {
const instance = L.tileLayer.webGis(props.url, {...props})
return { instance, context }
}
Then you need another function that will handle any updates you want to trickle down into your component. For example, if a certain prop of your component changes, you need to explicitly tell react-leaflet to update the underlying leaflet instance of that component:
const updateWebGisLayer = (instance, props, prevProps) => {
if (prevProps.url !== props.url) {
if (instance.setUrl) instance.setUrl(props.url)
}
if (prevProps.userId !== props.userId) {
if (instance.setUserId) instance.setUserId(props.userId)
}
}
You need these setter functions to tell react-leaflet that if the url
or userId
(or whatever) prop changes in react, it needs to rerender the leaflet layer. setUrl
already exists on L.TileLayer
, but you'll need to define a setUserId
that updated the userId
option of the L.TileLayer.WebGis
instance. If you don't include these, your component will not update when its props changes.
To put it all together, you can use the createLayerComponent
factory function:
const WebGisLayer = createLayerComponent(createWebGisLayer, updateWebGisLayer)
export WebGisLayer
WebGisLayer
is now a react component that you can use as a child of a MapContainer
const App = () => {
const [userId, setUserId] = useState('user123')
return (
<MapContainer center={center} zoom={zoom}>
<WebGisLayer
url="some_url"
userId={userId}
otherPropsYouNeed={otherProps} />
</MapContainer>
)
}
When the component loads it will run your leaflet code and add the leaflet component to the map. If the userId
changes due to some setstate call, your updateWebGisLayer
function tells react-leaflet to update the underlying leaflet component.
There's a lot of ways to do this, but this is the one I think is most straightforward. I haven't had a chance to test this code so you'll inevitably have to play around with it to get it working, but this should get you started.