Hook to get map instance inside or outside RMap.
import { type Map } from "maplibre-gl";
import { RMap, useMap } from "maplibre-react-components";
function ChildComponent() {
// This component is inside RMap.
// your MapLibre map instance is always defined and cannot be null.
const map: Map = useMap();
return null;
}
export default function App() {
return (
<RMap>
<ChildComponent />
</RMap>
);
}
If you use useMap inside <RMap /> and you're using TypeScript it is better not to specify an id for your useMap hook because
you will not have to handle the null case. But keep in mind that this is just for TypeScript because map is
always available when you are in <RMap />.
If you want to access your map instance outside of RMap you must wrap your application in
a <RMapContextProvider /> component. Moreover you must give an id to <RMap /> and
provide this same id to useMap.
This might seem useless to provide an id if your application contains only one map instance but this precaution help TypeScript to return the correct type.
import { type Map } from "maplibre-gl";
import { RMapContextProvider, RMap, useMap } from "maplibre-react-components";
function ChildComponent() {
// If you use `useMap` outside <RMap /> you need to set the <RMap> `id` prop
// and specify this id in your hook.
// your map instance can be null.
const map: Map | null = useMap("my-map");
return (
<div>
<div>map is {map !== null ? "available": "not available"}</div>
<RMap id="my-map"></RMap>
</div>
);}
export default function App() {
return (
<RMapContextProvider>
<ChildComponent />
</RMapContextProvider>
);
}
import { type Map} from "maplibre-gl";
// when used inside <RMap />
export function useMap(): Map;
// when used outside <RMap />
export function useMap(id: string): Map | null;