Search code examples
react-leaflet

Add layer to react-leaflet MapContainer after 1st render (dynamically)


is it possible to add a layer to react-leaflet v4 dynamically? i.e. after the MapContainer and all its children have rendered.

use case example: user selects a date from a calendar widget to load a specific image to the map e.g. a TileLayer. The problem is that the dates go back years, so I cannot simply preload a component for each image and just show it if the user selects it.

I am looking for a best practice for doing this in react-leaflet. It is very simple with plain JS and leaflet... But I'm new to react-leaflet and things work a bit differently.

TIA


Solution

  • [extracted from OP's comment]

    In case someone comes across this in future, the simplest way is to create a component:

    import { useEffect } from 'react'
    import { useLeafletContext } from '@react-leaflet/core'
    import L from 'leaflet'
    
    function Square(props) {
      const context = useLeafletContext()
    
      useEffect(() => {
        const bounds = L.latLng(props.center).toBounds(props.size)
        const square = new L.Rectangle(bounds)
        const container = context.layerContainer || context.map
        container.addLayer(square)
        return () => {
          container.removeLayer(square)
        }
      })
      return null
    }