reactjsreact-leafletreact-leaflet-v3

Render Map child from outside MapContainer


I would like to render a child inside <MapContainer> from outside the initial MapContainer. Is this possible somehow?

In react-leaflet-v3 I render a lot of items on the map by passing the map object via a reference. But for my current situation I wold like to render a react button on top of the map based on routing.

One way of doing this is to add nest <Route />. inside the MapContainer. This however is not ideal because of the scattered route behaviour...

Is it possible in another way?


Solution

  • I used the portal way to solve my problem:

    In my map-container, this is happening:

    const [control, setControl] = useState(null);
    const handleRef = useCallback((instance) => setControl(instance), [
      setControl,
    ]);
    ...
    
    
    <MapContainer ...>
       ...
       <div className="mapcontrol-top-left" ref={handleRef}></div>
    </MapContainer>
    

    In a totally different component, where conditionally I want to show something on the Map, I do this (using Material-UI Portal & Fab component):

    <Portal container={props.control}>
      <Fab size="medium">
        <EditIcon />
      </Fab>
    </Portal>
    

    The material-ui Portal component is easy to use and adds convenience, but a native React Portal will also do the trick...