React & other frameworks
<ml-map> is a standard custom element, so React, Vue, Svelte and other
frameworks render it like any other tag. There is no wrapper component to
install: register the element once, import MapLibre’s CSS, and point src at
a YAML file. Render the element in your components; the
JavaScript API (MapRenderer) is not the
framework path. A re-render with a changed config updates the map in
place, so the element fits a framework’s data flow without a key or a
remount.
Quick start
Section titled “Quick start”This makes a new Vite + React app that shows a map from a YAML file. In an app you already have, skip the first command.
1. Create the app and install the packages:
npm create vite@latest my-map -- --template react-tscd my-mapnpm installnpm install @maplibre-yaml/core maplibre-gl2. Register the element and import MapLibre’s CSS once. Add these lines
at the top of src/main.tsx:
import { setWorkerUrl } from "maplibre-gl";import workerUrl from "maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url";import "maplibre-gl/dist/maplibre-gl.css";import "@maplibre-yaml/core/register";
// maplibre-gl 6 is ESM-only and cannot find its worker inside a bundle;// point it there before the first map renders (v4/v5: drop these lines).setWorkerUrl(workerUrl);3. Give TypeScript the element’s typings. Create src/ml-map.d.ts (any
.d.ts file under src/ works) with this one line:
/// <reference types="@maplibre-yaml/core/react" />Without it, npm run build stops with Property ‘ml-map’ does not exist on
type ‘JSX.IntrinsicElements’.
4. Save the map document as public/map.yaml. Vite serves the files in
public/ from the site root, so this one is at /map.yaml:
type: mapid: earthquake-mapconfig: center: [-160, 20] zoom: 1 mapStyle: "https://tiles.openfreemap.org/styles/liberty"layers: - id: earthquakes type: circle source: type: geojson url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson" paint: circle-radius: ["interpolate", ["linear"], ["get", "mag"], 1, 2, 7, 20] circle-color: "#e74c3c" circle-opacity: 0.7 interactive: click: popup: - h3: - property: place5. Render it. Save this component as src/SrcMap.tsx:
import "@maplibre-yaml/core/register";
// public/map.yaml is served at /map.yaml.export function SrcMap() { return <ml-map src="/map.yaml" style={{ display: "block", height: "400px" }} />;}and render it from src/App.tsx:
// src/App.tsx: the whole file. It replaces the starter's demo page.import { SrcMap } from "./SrcMap";
export default function App() { return <SrcMap />;}6. Run npm run dev and open the address it prints
(http://localhost:5173). The page shows the past week’s earthquakes as red
circles, sized by magnitude, on a world map; click one to see where it
happened.
Files that src and the YAML’s url:s point at go in the framework’s static
folder: public/ in Vite and Next.js, static/ in SvelteKit. Under another
bundler, the worker lines differ:
Installation.
To try map documents before you put them in your app, use the
playground.
Common tasks
Section titled “Common tasks”Most recipes here are components that load the quick start’s /map.yaml.
Save one in src/ under its component’s name, and render it from
src/App.tsx in place of <SrcMap />.
Respond to a click
Section titled “Respond to a click”Clicking a feature fires ml-map:layer-click, with the feature in
event.detail.feature. On React 19, listen with an onml-map:layer-click
prop; the typings give the handler its event’s type. Save this as
src/ClickedPlace.tsx:
import "@maplibre-yaml/core/register";import { useState } from "react";
// React 19: an `onml-map:*` prop listens for that ml-map:* event.export function ClickedPlace() { const [place, setPlace] = useState<string | null>(null);
return ( <> <ml-map src="/map.yaml" onml-map:layer-click={(event) => setPlace(event.detail.feature.properties.place)} style={{ display: "block", height: "400px" }} /> <p>Clicked: {place ?? "nothing yet"}</p> </> );}Click a red circle: under the map, a line such as Clicked: 19 km S of Makurazaki, Japan shows where that earthquake happened.
The colon makes onml-map:layer-click a namespaced JSX attribute. Vite and
TypeScript compile it; if your JSX compiler rejects namespaced attributes,
spread it in: {...{ "onml-map:layer-click": handler }}.
React 18 ignores onml-map:* props. This ClickedPlace works on React 18 and
19: it adds the listener through a ref and removes it in the effect’s cleanup.
import "@maplibre-yaml/core/register";import type { MLMap, MLMapEventMap } from "@maplibre-yaml/core/register";import { useEffect, useRef, useState } from "react";
// React 18 and 19: listen on the element through a ref.export function ClickedPlace() { const ref = useRef<MLMap>(null); const [place, setPlace] = useState<string | null>(null);
useEffect(() => { const el = ref.current!; const onClick = (event: MLMapEventMap["ml-map:layer-click"]) => setPlace(event.detail.feature.properties.place); el.addEventListener("ml-map:layer-click", onClick); return () => el.removeEventListener("ml-map:layer-click", onClick); }, []);
return ( <> <ml-map ref={ref} src="/map.yaml" style={{ display: "block", height: "400px" }} /> <p>Clicked: {place ?? "nothing yet"}</p> </> );}Every event and its detail is listed in the
<ml-map> reference.
Use the MapLibre map
Section titled “Use the MapLibre map”mapReady() resolves with the MapLibre
Map once the
document has loaded, so all of MapLibre’s API is there: flyTo,
setPaintProperty, queryRenderedFeatures, on. This button flies to Japan:
import "@maplibre-yaml/core/register";import type { MLMap } from "@maplibre-yaml/core/register";import { useRef } from "react";
export function FlyToJapan() { const ref = useRef<MLMap>(null);
// mapReady() resolves with the MapLibre map once the document has loaded. const flyToJapan = async () => { const map = await ref.current!.mapReady(); map.flyTo({ center: [138, 37], zoom: 4.5 }); };
return ( <> <button type="button" onClick={flyToJapan}> Fly to Japan </button> <ml-map ref={ref} src="/map.yaml" style={{ display: "block", height: "400px" }} /> </> );}Once the map has loaded, ref.current.getMap() returns the same map without
waiting (before then it returns null).
Listen with a useMapEvent hook
Section titled “Listen with a useMapEvent hook”The ref, the listener and the cleanup are the same for every event, so a hook
can hold them. Save this as src/useMapEvent.ts (it is not part of the
package). It calls the newest handler without re-subscribing on every render,
and StrictMode’s extra mount still leaves one listener:
import { useEffect, useRef, type RefObject } from "react";import type { MLMapEventMap } from "@maplibre-yaml/core/register";
// Listen for an ml-map:* event on the element in `ref` (or on an element// around maps: the events bubble). Works on React 18 and 19.export function useMapEvent<K extends keyof MLMapEventMap>( ref: RefObject<HTMLElement | null>, type: K, handler: (event: MLMapEventMap[K]) => void) { // Call the newest handler without re-subscribing on every render. const latest = useRef(handler); useEffect(() => { latest.current = handler; });
useEffect(() => { const el = ref.current; if (!el) return; const listener = (event: Event) => latest.current(event as MLMapEventMap[K]); el.addEventListener(type, listener); return () => el.removeEventListener(type, listener); }, [ref, type]);}A component then names the event and the handler. Each click adds one place to the list:
import "@maplibre-yaml/core/register";import type { MLMap } from "@maplibre-yaml/core/register";import { useRef, useState } from "react";import { useMapEvent } from "./useMapEvent";
export function ClickedPlaces() { const ref = useRef<MLMap>(null); const [places, setPlaces] = useState<string[]>([]);
useMapEvent(ref, "ml-map:layer-click", (event) => setPlaces((list) => [...list, event.detail.feature.properties.place]) );
return ( <> <ml-map ref={ref} src="/map.yaml" style={{ display: "block", height: "400px" }} /> <ol> {places.map((place, i) => ( <li key={i}>{place}</li> ))} </ol> </> );}A map from a config object
Section titled “A map from a config object”When your code builds the document, pass it as config. A JSON string works
on React 18 (which sets it as the attribute) and React 19 (which sets the
property):
import "@maplibre-yaml/core/register";import type { MapBlock } from "@maplibre-yaml/core";
export function ConfigMap({ config }: { config: MapBlock }) { // A JSON string works on React 18 (set as the attribute) and React 19 // (set as the property). An equal string never re-renders the map. return ( <ml-map config={JSON.stringify(config)} style={{ display: "block", width: "100%", height: "400px" }} /> );}A changed config is applied to the running map in place: layers and
sources that differ change by id, the camera moves only if the document’s
camera changed, and the map object and your listeners stay (a changed
mapStyle rebuilds the map, at the current camera). An equal one does
nothing, so a component that rebuilds the same document on every render
doesn’t touch the map. For very large inline GeoJSON, keep the value stable
(module-level or memoized): the comparison serializes it. An invalid first
document shows the “Configuration Error” card, as a YAML file would; an
invalid later one is refused with ml-map:update-rejected and the map kept
(Updating the document).
Read and change the map with a useMlMap hook
Section titled “Read and change the map with a useMlMap hook”A component that shows the document’s state: values, or changes the
document from a form, wants them as React state. This hook returns the
MapLibre map, the document the map shows and its state: values, kept
current by ml-map:load, ml-map:update-applied and ml-map:state-change,
with setState and update bound to the element. Save it as
src/useMlMap.ts (it is not part of the package):
import { useCallback, useEffect, useState, type RefObject } from "react";import type { Map as MapLibreMap } from "maplibre-gl";import type { MapBlock } from "@maplibre-yaml/core";import type { MLMap, MLMapEventMap, UpdateResult } from "@maplibre-yaml/core/register";
// The map, the document it shows and its `state:` values as React state,// plus `setState` and `update` bound to the element in `ref`. Works on// React 18 and 19; StrictMode's extra mount leaves one set of listeners.export function useMlMap(ref: RefObject<MLMap | null>) { const [map, setMap] = useState<MapLibreMap | null>(null); const [doc, setDoc] = useState<MapBlock | null>(null); const [state, setStateValues] = useState<Record<string, unknown>>({});
useEffect(() => { const el = ref.current; if (!el) return; // ml-map:load fires on the first render and after a basemap rebuild (a // new map object); ml-map:update-applied after an in-place update (the // same map, a new document). const sync = () => { setMap(el.getMap()); setDoc(el.getDocument()); setStateValues(el.getState()); }; const onState = (event: MLMapEventMap["ml-map:state-change"]) => setStateValues(event.detail.values); el.addEventListener("ml-map:load", sync); el.addEventListener("ml-map:update-applied", sync); el.addEventListener("ml-map:state-change", onState); if (el.isLoaded()) sync(); // the map loaded before this effect ran return () => { el.removeEventListener("ml-map:load", sync); el.removeEventListener("ml-map:update-applied", sync); el.removeEventListener("ml-map:state-change", onState); }; }, [ref]);
// Declared `state:` keys only: an undeclared key throws. const setState = useCallback( (values: Record<string, unknown>) => ref.current?.setState(values), [ref] ); // Resolves with the outcome: applied, rejected (map untouched), fallback // (a basemap change rebuilt the map) or superseded by a later update. const update = useCallback( (next: MapBlock): Promise<UpdateResult> => ref.current?.update(next) ?? Promise.resolve({ outcome: "rejected" }), [ref] );
return { map, document: doc, state, setState, update };}In a component, const { state, setState, update, document } = useMlMap(ref)
next to <ml-map ref={ref} …>: a <select> whose value is
state.scenario and whose onChange calls setState({ scenario }) follows
the map’s params panel and drives it, and a form that edits a copy of
document and calls update(next) gets back { outcome, summary } (or
errors, with the map untouched). The document’s state: block declares
the keys setState accepts
(State and parameters).
The React 19 props onml-map:update-applied, onml-map:update-rejected and
onml-map:state-change listen for the same events without a hook.
React 19: object config and event props
Section titled “React 19: object config and event props”React 19 sets custom-element props as properties, so config takes the object
itself, and attaches on* props as listeners
(Respond to a click): one per event,
onml-map:update-applied, onml-map:update-rejected and
onml-map:state-change included. React 18 ignores the event props, and the
typings reject an object config there:
import "@maplibre-yaml/core/register";import type { MapBlock } from "@maplibre-yaml/core";
// React 19 only: `config` takes the object itself (React 19 sets it as a// property), and `onml-map:*` props attach listeners, typed per event.export function EventPropsMap({ config, onLoad, onLayerClick,}: { config: MapBlock; onLoad: () => void; onLayerClick: (layerId: string) => void;}) { return ( <ml-map config={config} onml-map:load={() => onLoad()} onml-map:layer-click={(event) => onLayerClick(event.detail.layerId)} onml-map:error={(event) => console.error(event.detail.error ?? event.detail.errors) } style={{ display: "block", height: "400px" }} /> );}Slot children
Section titled “Slot children”React can render your own controls into the map’s corners
(slots).
The element moves slot children into the map, so render them
unconditionally: React may update what is inside them, but must not add or
remove the slotted elements themselves. Toggle one with hidden or CSS
instead.
import "@maplibre-yaml/core/register";import type { MLMap } from "@maplibre-yaml/core/register";import { useRef } from "react";
export function MapWithControls({ src }: { src: string }) { const ref = useRef<MLMap>(null); const zoomBy = (delta: number) => { const map = ref.current?.getMap(); map?.easeTo({ zoom: map.getZoom() + delta, duration: 300 }); };
// Children with slot="top-left" (and the other corners, or "legend") are // placed in the map's corner, stacked with the built-in chrome. Render // slot children unconditionally: the element moves them into the map, so // React may update their contents but must not add or remove them. return ( <ml-map ref={ref} src={src} style={{ display: "block", height: "400px" }}> <div slot="top-left" className="map-buttons"> <button type="button" aria-label="Zoom in" onClick={() => zoomBy(1)}> + </button> <button type="button" aria-label="Zoom out" onClick={() => zoomBy(-1)}> − </button> </div> </ml-map> );}Mounting and unmounting
Section titled “Mounting and unmounting”Unmounting removes the element, and the element then destroys its MapLibre
map: no leaked canvas, and a remount creates exactly one new map.
StrictMode’s double-run effects do not re-create the element, so keep
listener setup in an effect that has a cleanup, as the recipes above do. A
config assigned from an effect (after the element has connected) is waited
for, so it renders without a passing “No configuration provided” error.
Story maps
Section titled “Story maps”<ml-scrollytelling> works the same way: the same register import defines
it, src points at a story file in public/, and its events are
ml-scrollytelling:chapter, ml-scrollytelling:action and
ml-scrollytelling:error (listen with a ref, as above). The typings cover
<ml-map> only, so in TypeScript a <ml-scrollytelling> tag needs your own
declaration. Writing the story file:
Writing a story file.
Putting it together
Section titled “Putting it together”One component with all of the above: the clicked place, the zoom read from the
MapLibre map, and errors. ml-map:error carries detail.errors, a list of
{ path, message }, when the document can’t be fetched, parsed or validated
(the map shows the same list), and one detail.error for anything else, such
as a basemap or data file that fails to load. It uses useMapEvent from
above:
import "@maplibre-yaml/core/register";import type { MLMap } from "@maplibre-yaml/core/register";import { useEffect, useRef, useState } from "react";import { useMapEvent } from "./useMapEvent";
export function EarthquakeMap() { const ref = useRef<MLMap>(null); const [place, setPlace] = useState<string | null>(null); const [zoom, setZoom] = useState<number | null>(null); const [problem, setProblem] = useState<string | null>(null);
useMapEvent(ref, "ml-map:layer-click", (event) => setPlace(event.detail.feature.properties.place) ); // A document that can't be fetched, parsed or validated reports `errors` // (and the map shows them); anything else reports one `error`. useMapEvent(ref, "ml-map:error", ({ detail }) => setProblem(detail.error ? detail.error.message : detail.errors.map((e) => e.message).join("; ")) );
useEffect(() => { let live = true; let stop = () => {}; ref.current!.mapReady().then( (map) => { if (!live) return; const onZoom = () => setZoom(map.getZoom()); onZoom(); map.on("zoomend", onZoom); stop = () => map.off("zoomend", onZoom); }, () => {} // the document failed: ml-map:error has the details ); return () => { live = false; stop(); }; }, []);
return ( <> <ml-map ref={ref} src="/map.yaml" style={{ display: "block", height: "400px" }} /> <p> Zoom {zoom?.toFixed(1) ?? "…"} · clicked: {place ?? "nothing yet"} </p> {problem && <p>Map problem: {problem}</p>} </> );}Under the map: Zoom 1.0 · clicked: nothing yet. Click a circle and its place
appears; zoom in and the number follows. Break map.yaml (delete a ]) and a
second line reads Map problem: YAML syntax error….
What differs between frameworks
Section titled “What differs between frameworks”src works the same everywhere. Three things differ: how a config object
reaches the element, how you listen for ml-map:* events, and TypeScript.
config object | ml-map:* events | TypeScript | |
|---|---|---|---|
| React 19 | Set as a property: the object (keep it stable) or a JSON string | onml-map:load={…} props, or a ref + addEventListener | @maplibre-yaml/core/react: typed config and event props |
| React 18 | Set as an attribute: a JSON string only (an object becomes "[object Object]") | A ref + addEventListener | @maplibre-yaml/core/react: an object config is a type error |
| Vue 3 | Set as a property: pass the object | @ml-map:load="…" | Works (add isCustomElement, below) |
| Svelte 5 | Set as a property: pass the object | bind:this + addEventListener | Works out of the box |
A JSON string plus a ref-based listener works on both React majors.
TypeScript with React
Section titled “TypeScript with React”React’s JSX types do not know <ml-map>, so without the typings tsc
reports Property ‘ml-map’ does not exist on type ‘JSX.IntrinsicElements’.
The reference line in the quick start adds them
(import "@maplibre-yaml/core/react"; in any module works too; it is empty
at runtime). They adapt to @types/react 18 or 19, type useRef<MLMap>(null)
so mapReady(), getMap(), update() and setState() are typed, type the
camera prop ("document" or "host": whether a changed document may move
the camera), and accept slot children and an inline
<script type="text/yaml">. MLMap, MLMapEventMap and UpdateResult
come from @maplibre-yaml/core/register.
Next.js
Section titled “Next.js”Client components still render on the server (App Router included). From
@maplibre-yaml/core 0.9.1, the register module is safe to import there: on
the server it only loads, and it defines the element when the client bundle
runs in the browser. Import it at the top of a "use client" file:
"use client";import "@maplibre-yaml/core/register";
export default function YamlMap({ src }) { return <ml-map src={src} style={{ display: "block", height: "400px" }} />;}The server sends a plain <ml-map> tag, which upgrades in the browser. Put
map.yaml in public/, and import the MapLibre CSS in app/layout. On
maplibre-gl 6, call setWorkerUrl() with your bundler’s URL for the worker in
the same file as the register import
(Installation).
On 0.9.0 and earlier, that import fails the build with
ReferenceError: HTMLElement is not defined. There, register the element
from an effect instead:
"use client";import { useEffect } from "react";
export default function YamlMap({ src }) { useEffect(() => { import("@maplibre-yaml/core/register"); }, []);
return <ml-map src={src} style={{ display: "block", height: "400px" }} />;}Point src at a file in public/, and reach the map through a template ref:
<template> <ml-map ref="mapEl" src="/map.yaml" style="width: 100%; height: 400px; display: block;" @ml-map:error="(e) => console.error(e.detail.error ?? e.detail.errors)" /></template>
<script setup>import "@maplibre-yaml/core/register";import { onMounted, ref } from "vue";
const mapEl = ref(null);
onMounted(async () => { const map = await mapEl.value.mapReady(); map.flyTo({ zoom: 3 });});</script>For a document built in code, bind the object: :config="doc" (Vue sets it
as a property). Tell Vue’s compiler that ml-* tags are custom elements.
Without this, every render logs Failed to resolve component: ml-map in
development:
import { defineConfig } from "vite";import vue from "@vitejs/plugin-vue";
export default defineConfig({ plugins: [ vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith("ml-") }, }, }), ],});Vue templates reject <script> tags, so an inline <script type="text/yaml">
doesn’t work there; use src or config. vue-tsc accepts <ml-map> by
default; under strictTemplates it reports the element as unknown.
Svelte
Section titled “Svelte”Point src at a file in static/ (SvelteKit) or public/ (Vite), and
reach the map through bind:this:
<script> import "@maplibre-yaml/core/register"; import { onMount } from "svelte";
let mapEl;
onMount(() => { const onError = (e) => console.error(e.detail.error ?? e.detail.errors); mapEl.addEventListener("ml-map:error", onError); mapEl.mapReady().then((map) => map.flyTo({ zoom: 3 }), () => {}); return () => mapEl.removeEventListener("ml-map:error", onError); });</script>
<ml-map bind:this={mapEl} src="/map.yaml" style="width: 100%; height: 400px; display: block;"></ml-map>For a document built in code, pass the object: {config} (Svelte 5 sets it
as a property). Close the tag explicitly: Svelte 5 warns about self-closing
non-void elements such as <ml-map />. onml-map:load={…} attaches a
listener, but Svelte warns that attribute names should not contain :, so
use bind:this as shown. svelte-check accepts <ml-map> and its
attributes out of the box. With lang="ts", type the binding as
let mapEl: MLMap (imported from @maplibre-yaml/core/register).
SvelteKit renders components on the server too. From @maplibre-yaml/core
0.9.1 the register import above works there as it is. On 0.9.0 and earlier
it fails with HTMLElement is not defined; move it into onMount:
onMount(() => { import("@maplibre-yaml/core/register"); }).
Reference
Section titled “Reference”<ml-map>reference: every attribute, property, method and event.examples/react: a Vite + React + TypeScript app with every React snippet on this page, built and browser-tested against React 18 and React 19. Itsrecipes.htmlruns the click, MapLibre, hook and putting-it-together recipes on the quick start’s map document.
Troubleshooting
Section titled “Troubleshooting”Problems every map shares are in Troubleshooting.
ReferenceError: HTMLElement is not definedduring a server render or build:@maplibre-yaml/core0.9.0 or earlier, imported on the server. Upgrade, or register the element from an effect (Next.js).- The map is blank and the element’s
configattribute reads[object Object]: React 18 setsconfigas an attribute. PassJSON.stringify(doc). - The map reports Worker failed to load: maplibre-gl 6 needs the
setWorkerUrl()lines in your entry file (quick start). - The map shows YAML syntax error …
<!doctype html>: the YAML file isn’t in the static folder, so the server answered with your app’s HTML page. Move it topublic/(orstatic/in SvelteKit). - Vue logs Failed to resolve component: ml-map: add the
isCustomElementoption (Vue). - TypeScript: Property ‘ml-map’ does not exist on type ‘JSX.IntrinsicElements’: add the typings reference (TypeScript with React).