Create a New Map using React Leaflet

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 10 months ago

In this lesson, you will learn how to add a map to your React application using React Leaflet. We will walk through importing and configuring the Map and TileLayer components from React Leaflet to set up the new map.

Colby Fayock: [0:00] Once we have a React dev setup, we want to add leaflet and react-leaflet using yarn or npm. Once it's finished installing, we can start back up our development server. Now that our dependencies are installed, we can import { Map, TileLayer } from 'react-leaflet'.

[0:15] With our components imported, the first thing we want to do is create a Map component. On that Map, we want to add a center prop which is our latitude and longitude and a zoom prop which is the zoom level of our Map.

[0:25] Inside our Map we want add a TileLayer component. On that TileLayer, we want to add a url prop, which is the endpoint of our TileLayer, and an attribution prop so we can give credit to the service we're using for our TileLayer. Once we hit Save, we can open back our browser and see that it's not yet quite a map.

[0:40] To fix this, the first thing we want to do is import the leaflet.css from the leaflet source. Additionally, leaflet requires a fixed height on its container. Inside our css file, we want to add a leaflet-container class which will add a width of 100vw and height of 100vh. Once we hit Save, we can open back up a browser and see our map.

[1:00] To review, the first thing we did was install leaflet and react-leaflet. With react-leaflet installed, we imported our Map and our TileLayer to create our map components. Then we imported the leaflet.css and we added our own CSS snippet to fix the height. With that, we have our map.