Basic Introduction
React Leaflet provides bindings between React and Leaflet. It does not replace Leaflet but leverages it to abstract Leaflet layers as React components.
React Leaflet uses React’s context API to make some Leaflet elements instances available to children’s elements that need it.
Each Leaflet map instance has its own React context, created by the MapContainer
component. Other components and hooks provided by React Leaflet can only be used as descendants of a MapContainer.
Lifecycle process
- The
MapContainer
renders a container<div>
element for the map. If theplaceholder
prop is set, it will be rendered inside the container<div>
. - The
MapContainer
instantiates a Leaflet Map for the created<div>
with the component properties and creates the React context containing the map instance. - The
MapContainer
renders its children components. - Each child component instantiates the matching Leaflet instance for the element using the component properties and context, and adds it to the map.
- When a child component is rendered again, changes to its supported mutable props are applied to the map.
- When a component is removed from the render tree, it removes its layer from the map as needed.
Installation
’npm‘ can be used to install React leaflet and its dependencies.
React, React DOM and Leaflet are required peer dependencies. We must add them to our project if they are not already installed:
npm install react react-dom leaflet
Then we can install React Leaflet:
npm install react-leaflet
Modules can then be imported using bare specifiers when supported by a bundler such as webpack
import { MapContainer } from ‚react-leaflet/MapContainer‘
import { TileLayer } from ‚react-leaflet/TileLayer‘
import { useMap } from ‚react-leaflet/hooks‘
Alternatively, all the components and hooks can be imported from the module entry-point:
import { MapContainer, TileLayer, useMap } from ‚react-leaflet‘
Setup
Use the following code:
<MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution=’© <a href=“https://www.openstreetmap.org/copyright“>OpenStreetMap</a> contributors‘
url=“https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png“
/>
<Marker position={[51.505, -0.09]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
Result
Example to visualize multiple locations with markers
Output
Still having trouble? Use the react-leaflet
tag on Stack Overflow. 😉