0

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?

Hoetmaaiers
  • 3,413
  • 2
  • 19
  • 29
  • 1
    Do you want to render a button outside the MapContainer? Doing what? Can you explain the behavior you want to implement when clicking the button? – kboul Jan 27 '21 at 15:38
  • The behaviour could be updating the browser history stack to route a nested page (with the map still visible). – Hoetmaaiers Jan 28 '21 at 09:10
  • I found the usage of a `Portal` to help me in doing this :) – Hoetmaaiers Jan 28 '21 at 10:29
  • That's nice because I do not get how the behavior you want to implement is connected with MapContainer's children. It seems that is not related with a first glance but perhaps I did not understand what you want to achieve – kboul Jan 28 '21 at 10:35
  • Mind putting in an answer what you did? Now I'm curious – Seth Lutske Feb 03 '21 at 16:51

1 Answers1

0

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...

Hoetmaaiers
  • 3,413
  • 2
  • 19
  • 29