Sometimes, we want to add a Leaflet map into a React component.
In this article, we’ll look at how to add a Leaflet map into a React component.
How to add a Leaflet map into a React component?
To add a Leaflet map into a React component, we can use the React Leaflet library.
To install it, we run:
npm i leaflet react-leaflet
Then we can add a map by writing:
import React from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
const position = [51.505, -0.09];
export default function App() {
return (
<MapContainer
style={{ height: "300px" }}
center={position}
zoom={13}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
}
And we add the Leaflet CSS to the index.html file:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
We add the MapContainer
with the defined height so that Leaflet can render the map properly.
Also, set set the center
prop to the latitude and longitude of the center of the map.
zoom
sets the default zoom level.
scrolLWheelZoom
lets us zoom the map with the scroll wheel if it’s true
.
We use the TileLayer
component to add a map layer.
And we use Marker
to add a marker.
The Popup
component lets us display a popup when we click on a marker.
Now we should see a map displayed.
Conclusion
To add a Leaflet map into a React component, we can use the React Leaflet library.