Follow along with this sandbox on StackBlitz

When  working with React-Leaflet, there will be times when we want to add our own custom controls to the map. Let’s say that we want to show our users how to get from Point A to Point B.  React-Leaflet doesn’t come with a routing feature straight out of the box, but we can use  third-party plugins to get this done quick and easy.  Leaflet-Routing-Machine gives us exactly the functionality that we want, but how can we get this vanilla Leaflet control plugin to work with our React-Leaflet application?

Using React’s useRef Hook

It’s important to remember that even though we are using React,  Leaflet will be handling the DOM rendering for our map. This means that we are able to access our Leaflet elements by utilizing  React’s useRef hook.

If we take a look at the  docs for the MapContainer component, we see that it has a whenCreated prop:

Map Container Props list from the documentation

#programming #react #leaflet #javascript

How to create a React-Leaflet control component with Leaflet-Routing-Machine
2.95 GEEK