I am using react-leaflet.
For example I want to set bounds to map outside of the file where <MapContainer>
is called.
For this I need to use const map = useMap();
. How do I connect useMap() with the file where was called?
Or to clarify even more.. I want to connect with the map outside of the map file to be enable to add/remove stuff. For example I want to enable markers outside of the file where <MapContainer>
is called.
Advertisement
Answer
ghybs is probably right in that you’re probably thinking of doing something that doesn’t truly require the L.map
object in an ancestor of the MapContainer
. Especially if you’re simply talking about using map Marker
components – theyre only ever useful as children of a map. That being said, what you’re talking about doing is simple to set up. An example of how to make the underlying L.map
object available is right there in the react-leaflet docs.
A quick example:
const App = () => { const [mapRef, setMapref] = useState(); return ( <> <Map setMapRef={setMapRef} /> <SomewhereElse mapRef={mapRef} /> </> ) } const Map = ({ setMapRef }) => { return <MapContainer whenCreated={setMapRef} /> }
Once the MapContainer
loads the leafletmap, whenCreated
is fired, which then fires the callback setMapRef
. The L.map
instance is now saved to the mapRef
state variable in App
, and is available there to be used SomewhereElse
.