In this lesson, you will learn how to use React hooks to interface with the Leaflet Map API in React Leaflet. We'll connect a ref to our Map component using the useRef hook and then use the useEffect hook to access that ref, find our Map instance, and use it to fly to a new location.
Instructor: [0:00] We're going to start off with a basic map focused on the United States. Inside our code, we're importing a Map and a TileLayer from react-leaflet. Our goal here is to be able to utilize the Map API.
[0:10] To do that, the first thing we want to do is import the useRef hook so that we can use it on the Map. Next, let's create a mapRef constant that uses the useRef hook, and then we want to add that ref to the Map itself.
[0:21] If we use console.log to show the value of this mapRef, we'll see that when the Map renders, it's still undefined. To work with our ref, we'll want to use a useEffect hook. Let's import useEffect from react. We can create an instance of us using the useEffect hook.
[0:36] We'll also want to add a dependency of mapRef. Inside hook, let's try to console.log out that mapRef again. In our browser, we can now see the current value is our Map. Now that we can actually access our mapRef, let's destructure it to make it easier to use.
[0:49] Let's also set a default value of an empty object in case mapRef isn't available. Inside current, our Map is actually stored on the leafletElement property. Let's also destructure our leafletElement from current. To make things easy to read, I'd like to rename it map. Now if we console.log out our map, we can see a new instance from our leaflet API.
[1:11] This gives us access to all the options and methods available on the native map instance. To test this out, let's make our map fly somewhere. We're going to use setTimeout to give the map a little bit of time to load. We can just set that as a one-second delay. In order for a map to fly somewhere, we need the location.
[1:27] We're going to create magicKingdomLatLng inside it's coordinates. Now we can use the map.flyto function, pass it our LatLng, set the zoom level, and give it a duration of three seconds, and watch our map fly to Magic Kingdom.
[1:42] To review, we're importing useRef creating a mapRef and adding it to our map. We also import a useEffect hook, which allows us to grab that mapRef and find our map instance which we can then use to fly to a location. With that, we're using react hooks to interface with our map.
thanks for the heads up - if you want to see a way to handle this, you can check out this example: https://github.com/colbyfayock/gatsby-starter-leaflet/blob/master/src/pages/index.js#L100
Hi... it seems newest version of react leaflet using <Map Container> does not support accessing map via ref (https://github.com/PaulLeCam/react-leaflet/issues/841) and one has to rely on useMap hook provided by module.
Just mentioning...