Max SchmittMS
13th February 2022

React Leaflet: Opening Popups Programmatically

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.

Starting Point: A Map that Renders a Marker with a Popup

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">
<MapContainer
style={{ width: 500, height: 500 }}
center={MAP_CENTER}
zoom={13}
>
<TileLayer
attribution='&copy; <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>
)
}

Showing the Marker and Popup Programmatically with React Leaflet

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.current
if (!map) {
return
}
map.flyTo(MARKER_POSITION, 13)
const marker = markerRef.current
if (marker) {
marker.openPopup()
}
}
return (
<div className="App">
<MapContainer
whenCreated={(map) => {
mapRef.current = map
}}
style={{ width: 500, height: 500 }}
center={MAP_CENTER}
zoom={13}
>
<TileLayer
attribution='&copy; <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.

Image of my head

About the author

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.