React-Leaflet provides an abstraction of ๐ Leaflet as โ๏ธย React components.
It does not replace Leaflet, only leverages โ๏ธย React's lifecycle methods to call the relevant Leaflet handlers. You can read more information about the lifecycle process in the introduction page of this documentation. Please make sure you understand all the core concepts and limitations to evaluate if this library is appropriate for your needs.
This documentation only presents concepts specific to React-Leaflet, you should already be familiar with both React and Leaflet to use this library. Otherwise, please make sure to go through React and Leaflet's getting started guides and examples first.
React-Leaflet allows to convert this ๐ sample code from Leaflet's documentation:
import L from 'leaflet'
const position = [51.505, -0.09]
const map = L.map('map').setView(position, 13)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map)
L.marker(position)
.addTo(map)
.bindPopup('A pretty CSS3 popup. <br> Easily customizable.')
to React components:
import React from 'react'
import { render } from 'react-dom'
import { Map, Marker, Popup, TileLayer } from 'react-leaflet'
const position = [51.505, -0.09]
const map = (
<Map center={position} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution="© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
/>
<Marker position={position}>
<Popup>A pretty CSS3 popup.<br />Easily customizable.</Popup>
</Marker>
</Map>
)
render(map, document.getElementById('map-container'))
Note that the <Map>
component creates its own <div>
container for the map, it does not get attached to an existing node.
The example code above is only meant to present the syntax change, it will not work as-is.
You can run an example code using React-Leaflet in โถ๏ธ this CodePen.