Leaflet is great for web applications that need to show information on maps. And if you're using React, you're probably using the useful React Leaflet package.
When working with Leaflet through React, you'll need to get used to using a few of the APIs in a more imperative, non-Reacty way.
In this post, I'll show you how to reveal a marker with its popup on a Map rendered by React Leaflet.
Let's say you have the following map which shows a single marker:
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'const MAP_CENTER = [52.52, 13.405]const MARKER_POSITION = [52.49913882549316, 13.418318969833383]function App() {return (<div className="App"><MapContainerstyle={{ width: 500, height: 500 }}center={MAP_CENTER}zoom={13}><TileLayerattribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/><Marker position={MARKER_POSITION}><Popup>Hello I'm a popup!</Popup></Marker></MapContainer></div>)}
Now let's add a button we can click to show the marker and popover.
For this we'll need references to the map itself as well as the marker created by Leaflet.
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'import { useRef } from 'react'const MAP_CENTER = [52.52, 13.405]const MARKER_POSITION = [52.49913882549316, 13.418318969833383]function App() {const mapRef = useRef(null)const markerRef = useRef(null)const onClickShowMarker = () => {const map = mapRef.currentif (!map) {return}map.flyTo(MARKER_POSITION, 13)const marker = markerRef.currentif (marker) {marker.openPopup()}}return (<div className="App"><MapContainerwhenCreated={(map) => {mapRef.current = map}}style={{ width: 500, height: 500 }}center={MAP_CENTER}zoom={13}><TileLayerattribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/><Marker ref={markerRef} position={MARKER_POSITION}><Popup>Hello I'm a popup!</Popup></Marker></MapContainer><button onClick={onClickShowMarker}>Show marker</button></div>)}
This is the result:
You can view the full code on CodeSandbox.
Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.
When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.
If you need help on a project, please reach out and let's work together.
To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.