19 chapters · 62 min
Skills
Chapter 18 of 19
Official integration patterns for Mapbox GL JS across popular web frameworks (React, Vue, Svelte, Angular).
3 minutes · 751 words · 24 sections
This skill provides official patterns for integrating Mapbox GL JS into web applications using React, Vue, Svelte, Angular, and vanilla JavaScript. These patterns are based on Mapbox’s create-web-app scaffolding tool and represent production-ready best practices.
Recommended: v3.x (latest)
Installing via npm (recommended for production):
npm install mapbox-gl@^3.0.0 # Installs latest v3.xCDN (for prototyping only):
<!-- Replace VERSION with latest v3.x from https://docs.mapbox.com/mapbox-gl-js/ -->
<script src="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.css" rel="stylesheet" />React: GL JS works with React 16.8+ (requires hooks). create-web-app scaffolds with React 19.x.
Vue: GL JS works with Vue 2.x+ (Vue 3 Composition API recommended).
Svelte: GL JS works with any Svelte version. create-web-app scaffolds with Svelte 5.x.
Angular: GL JS works with Angular 2+. create-web-app scaffolds with Angular 19.x.
Next.js: Minimum 13.x (App Router), Pages Router 12.x+.
npm install @mapbox/search-js-react@^1.0.0 # React
npm install @mapbox/search-js-web@^1.0.0 # Other frameworksoptimizeForTerrain option removedToken patterns (work in v2.x and v3.x):
const token = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN; // Use env vars in production
// Global token (works since v1.x)
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({ container: '...' });
// Per-map token (preferred for multi-map setups)
const map = new mapboxgl.Map({
accessToken: token,
Every Mapbox GL JS integration must:
map.remove() on cleanup to prevent memory leaksimport 'mapbox-gl/dist/mapbox-gl.css'Pattern: useRef + useEffect with cleanup
Note: These examples use Vite (the bundler used in
create-web-app). If using Create React App, replaceimport.meta.env.VITE_MAPBOX_ACCESS_TOKENwithprocess.env.REACT_APP_MAPBOX_TOKEN. See Token Management Patterns (opens in a new tab) for other bundlers.
import { useRef, useEffect } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
function MapComponent() {
const mapRef = useRef(null); // Store map instance
const mapContainerRef = useRef
Key points:
useRef for both map instance and containeruseEffect with empty deps []map.remove()import { useRef, useEffect, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import { SearchBox } from '@mapbox/search-js-react';
import 'mapbox-gl/dist/mapbox-gl.css';
const accessToken =
Install:
npm install @mapbox/search-js-react # React
npm install @mapbox/search-js-web # Vanilla/Vue/SvelteBoth packages include @mapbox/search-js-core as a dependency. Only install -core directly if building a custom search UI.
Key configuration options:
accessToken: Your Mapbox public tokenmap: Map instance (must be initialized first)mapboxgl: The mapboxgl library referenceproximity: [lng, lat] to bias results geographicallymarker: Boolean to show/hide result markerplaceholder: Search box placeholder textAbsolute positioning (overlay):
<div
style={{
position: 'absolute',
top: 10,
right: 10,
zIndex: 10,
width: 300
}}
>
<SearchBox {...props} />
</div>Common positions:
top: 10px, right: 10pxtop: 10px, left: 10pxbottom: 10px, left: 10px// BAD - Memory leak!
useEffect(() => {
const map = new mapboxgl.Map({ ... })
// No cleanup function
}, [])
// GOOD - Proper cleanup
useEffect(() => {
const map = new mapboxgl.Map({ ... })
return () =>
Why: Every Map instance creates WebGL contexts, event listeners, and DOM nodes. Without cleanup, these accumulate and cause memory leaks.
// BAD - Infinite loop in React!
function MapComponent() {
const map = new mapboxgl.Map({ ... }) // Runs on every render
return <div />
}
// GOOD - Initialize in effect
function MapComponent() {
useEffect(() => {
const map = new mapboxgl.
Why: React components re-render frequently. Creating a new map on every render causes infinite loops and crashes.
// BAD - map variable lost between renders
function MapComponent() {
useEffect(() => {
let map = new mapboxgl.Map({ ... })
// map variable is not accessible later
}, [])
}
// GOOD - Store in useRef
function MapComponent() {
const mapRef = useRef()
Why: You need to access the map instance for operations like adding layers, markers, or calling remove().
// BAD - Vue's reactivity wraps data() objects in a Proxy, breaking mapbox-gl internals!
export default {
data() {
return {
map: null // Will be wrapped in a Proxy
}
},
mounted() {
this.map = new mapboxgl.Map({ ... }) // Proxy breaks GL internals
Why: In Vue (especially Vue 3), data() properties are wrapped in a Proxy for reactivity. Mapbox GL JS internally checks object identity and uses properties that don’t survive proxy wrapping. Storing the map in data() causes subtle, hard-to-debug failures. Instead, assign the map instance directly as this.map in mounted() — properties assigned outside data() are not made reactive.
// BAD — blank map when the token/style fails
const map = new mapboxgl.Map({ ... });
// GOOD — surface failures
map.on('error', (e) => {
console.error(e.error || e);
// optionally show an on-page error message
});+esm<!-- BAD — often throws: does not provide export named 'makeBatchFromTable' -->
<script type="module">
import { MapboxOverlay } from 'https://cdn.jsdelivr.net/npm/@deck.gl/mapbox@9.0.0/+esm';
</script>
<!-- GOOD — UMD bundle (or esm.sh) -->
<script src="https://unpkg.com/deck.gl@9.1.14/dist.min.js"></script>
<script>
const
Use MapboxOverlay (Mapbox IControl), not a bare Deck as a map control.
draw.createIf you load mapbox-gl-draw, listen for draw.create (and update the UI from draw.getAll()). Half-deleted handlers that leave a dangling }); crash the page.
setStyle (no style.load rebind)map.setStyle(...) replaces the style tree. Custom sources/layers/handlers added earlier are wiped unless you re-attach them.
function onStyleReady() {
// re-add sources, layers, and interaction handlers here
}
map.on('style.load', onStyleReady);
document.querySelectorAll('[data-style]').forEach((btn) => {
btn.addEventListener('click', () => {
map.setStyle(btn.dataset.style);
Agent anti-pattern: style switcher buttons that call setStyle once with no style.load rebind. The first style works; every switch after looks broken.
Load these for framework-specific patterns and additional details:
references/vue.md — Vue Integration (mounted/unmounted lifecycle)references/svelte.md — Svelte Integration (onMount/onDestroy)references/angular.md — Angular Integration with SSR handlingreferences/vanilla.md — Vanilla JS (Vite) + Vanilla JS (CDN)references/web-components.md — Web Components (basic + reactive + usage in React/Vue/Svelte)references/nextjs.md — Next.js App Router + Pages Routerreferences/common-mistakes.md — Common Mistakes 4-7 + Testing Patternsreferences/token-management.md — Token Management per bundler + Style ConfigurationInvoke this skill when:
Install this repository
npx skills add mapbox/mapbox-agent-skills/plugin marketplace add mapbox/mapbox-agent-skillsSkills install per repository, not per chapter — the CLI has no documented per-skill form, so we do not print one.
Official integration patterns for Mapbox GL JS across popular web frameworks (React, Vue, Svelte, Angular). Covers setup, lifecycle management, token handling, search integration, and common pitfalls. Based on Mapbox's create-web-app scaffolding tool.
The verbatim description from this skill’s front matter — the string an agent matches on to decide whether to load it.
main, last pushed 7 August 2026.SKILL.md, not by matching a directory convention. One layout observed: skills/*/SKILL.md.h1 and no skipped levels:.claude-plugin/marketplace.json by Mapbox Plugin Marketplace, declaring 1 plugin. It is read for editorial metadata only — never as the skill index, which is always the repository tree./mapbox/mapbox-agent-skills.md.md10 files · 32 KB
Everything this skill ships beside its prose. All of it is set here, as subchapters of chapter 18.
Documentation the agent loads on demand, rather than up front.
Everything else published alongside the skill.