API
Export members
SizeOption: the union of available sizes.ProjectionOption: the union of available projections,"mercator" | "equalEarth".countryShortNames: the short country names used byzoom.countryLabelFormat, keyed by country code: the ISO 3166-1 alpha-3 code the UN uses (USA, ISR), and Natural Earth's for areas without one (Kosovo KOS, Northern Cyprus CYN, Somaliland SOL).projectionOptions: the list of available projections.MapTheme: the union of available themes,"default" | "atlas" | "atlasLight".mapThemeOptions: the list of available themes.ISOCode: the ISO code available to name countries.DataItem: the type for each country's value to be passed in thedataprop.Data: it's justDataItem[], for more convenience.CountryContext: the context in rendering each country, to be used in customization callbacks.Props: the props type for theWorldMapcomponent.mapRenderingLayers: the SVG layers in paint order (ocean,countries,disputed-territories,labels,region-labels,water-labels,country-labels,pins), each rendered as<g data-map-layer>.mapRenderingLayerOrdermaps a layer to its order andMapRenderingLayerIdis the layer type. See Styling and testing hooks.regions: the list of regions ({ name, code }) available in the librarydisputedTerritories: Tier 1 dispute metadata keyed by dispute ID (crimea,palestinian-territories,taiwan,kashmir,western-sahara,kosovo).disputeIds: the list of dispute IDs.disputesByCountryCode: map from rendered country code (e.g.UA,XK) to dispute ID.getDisputeById(id)/getDisputeByCountryCode(code): lookups returning aDisputeClassification(orundefinedfor a country code with no dispute).disputedTerritoryAreas: the territory shapes drawn byshowDisputedTerritories({ id, name, disputeId, administration }), e.g.crimea,aksai-chin,west-bank.DisputedTerritoryContext,DisputedTerritoryArea,DisputeClassification,DisputeDisplayGuidance,DisputeTier,DisputeStatus,DisputeReviewStatus,DisputeBorderStyle,DisputeLabelStrategy,DisputeId: types for the dispute metadata.ZoomOptions,ZoomState: the options of thezoomprop and the state passed toonZoomChange. See Zoom and pan.MapPin: one entry of thepinsprop.MapPinShape: itsshape,"pin" | "square" | "diamond".preloadDetailedCountryGeometry(): starts loading the detailed country borders drawn when zoomed in, for example when the pointer enters the map, so the first zoom shows them at once. See Detailed borders.DetailProvider,DetailProviderResult,DetailView,DetailLevel,DetailStatus,RegionCollection,RegionFeature,RegionCoverageStatus: types for region detail. See Region detail.createReadyDetailResult,createUnavailableDetailResult,createFailedDetailResult,createIdleDetailResult,isReadyDetailResult: helpers to build and checkDetailProviderResultvalues.CountryLabelCandidate: a placed country label (code, name, position and size in map coordinates).WorldMap: available both as named and default export. The actual component to be rendered.
Props
| Prop | Type | Description |
|---|---|---|
data | Data | Mandatory. Array of JSON records, each with country/value. |
size | SizeOption | 'responsive' | number | The size of your map. responsive mode fills the width of its container. See Sizing for details, and see Sizing example |
title | string | Any string for the title of your map. |
color | string | Color for highlighted countries. A standard color string. E.g. "red" or "#ff0000". |
tooltipBgColor | string | Tooltip background color. |
tooltipTextColor | string | Tooltip text color. |
valuePrefix | string | A string to prefix values in tooltips. E.g. "$" |
valueSuffix | string | A string to suffix values in tooltips. E.g. "USD" |
backgroundColor | string | Component background color. |
strokeOpacity | string | The stroke opacity of non selected countries. |
frame | boolean | Should a frame be drawn around the map. |
frameColor | string | Frame color. |
borderColor | string | Border color around each individual country. |
richInteraction | boolean | When turned on, double-click zooms the map 1x → 2x → 4x → reset, and + / - zoom in and reset from the keyboard. For full zoom and pan, use zoom. |
zoom | boolean | ZoomOptions | Opt-in zoom and pan with buttons, drag, double-click, keyboard and ctrl / ⌘ + wheel; also shows country labels. Off by default. See Zoom and pan and the Zoom example. |
onZoomChange | (state: ZoomState) => void | Called with the new zoom state each time the zoom or pan changes (not on mount). |
pins | MapPin[] | Markers with captions at longitude / latitude, with an optional color, shape and tooltip. Shown with or without zoom. Overlapping pins are dropped by priority, unless zoom.keepOverlappingPins keeps them all (hiding only clashing captions). A pin with a tooltip has a 24 px target and a tab stop, and its tooltip opens on hover and focus. |
pinColor | string | Fill color of the pin markers. Default #b91c1c. |
pinTextColor | string | Color of the pin captions. Default #1f2937. |
pinOutlineColor | string | Outline of the pin markers and halo behind their captions. Default #fff. |
labelColor | string | Color of the country labels shown with zoom. Default from the theme (#222 in the default theme). |
labelHaloColor | string | Halo drawn behind the country and region labels, for dark or busy maps. Default: none. |
dataList | boolean | "visible" | Also list each country with data, as its tooltip text, in an HTML list after the map, for screen readers and keyboard users. true hides it visually, "visible" shows it. Default false. |
showAntarctica | boolean | Draw Antarctica, as land without data (no tooltip, no data). Default true since 3.0.0; false gives the 2.x map. |
waterLabelColor | string | Colour of the ocean, sea and lake labels (zoom.showWater). Default from the theme. |
regionLabelColor | string | Colour of the region labels (zoom.showRegionLabels). Default from the theme (#555 in the default theme). |
detailLevel | 'countries' | 'regions' | regions draws the regions (states, provinces) of the countries in view from detailProvider, once zoomed in to zoom.regionDetailMinScale. Needs zoom. Default countries. See Region detail. |
detailProvider | DetailProvider | Supplies region geometry for detailLevel="regions", for example createRegionsDetailProvider() from the optional react-svg-worldmap-regions package. |
onDetailStatusChange | (status: DetailProviderResult) => void | Called when regions start loading, finish or fail for a country, and with idle when they are hidden again. |
theme | 'default' | 'atlas' | 'atlasLight' | Colour theme. Default default (the original look). atlas draws blue water, slate borders and light land, and keeps borders one pixel wide. atlasLight draws pale blue water only inside the globe, white land and soft grey borders. Colour props you set, including styleFunction, override the theme. See Themes and the Atlas theme example. |
projection | 'mercator' | 'equalEarth' | Map projection. Default mercator. equalEarth shows countries at their true relative size. See Projections and the Equal Earth example. |
🚧 type 🚧 | string | Select type of map you want, either "tooltip" or "marker". 📝 This functionality not only complicates the code, but is infrequently used and needs to be redesigned to make it better. For now it is deprecated and has no effect. 📝 |
styleFunction | (context: CountryContext) => React.CSSProperties | A callback function to customize styling of each country (see Custom styles example) |
hrefFunction | (context: CountryContext) => object | string | undefined | A callback function to bind an href link to each country. The return can be the target URL as a string or an object specifying props passed to the anchor element (e.g. href and target). (see Href binding example) |
tooltipTextFunction | (context: CountryContext) => string | A callback function to customize tooltip text (see Localization example) |
onClickFunction | (context: CountryContext & {event: React.MouseEvent}) => void | A callback function to add custom onclick logic (see Onclick action example) |
showDisputedTerritories | boolean | Draw the disputed territories (Crimea, the Kashmir areas, West Bank, Gaza, Western Sahara, Kosovo, Taiwan) as a red overlay above the countries. Off by default. (see Dispute metadata example) |
disputedTerritoryColor | string | Fill and border color of the disputed-territory overlay. Default #d32f2f. |
disputedTerritoryTooltipFunction | (context: DisputedTerritoryContext) => string | Tooltip text for each territory. The default lists status, recognized sovereign, controlling power, and parties. |
onDisputedTerritoryClick | (context: DisputedTerritoryContext & {event: React.MouseEvent}) => void | Called when a territory in the overlay is clicked. |
textLabelFunction | (mapWidth: number) => ({label: string} & TextProps)[] | A callback function to draw text labels on the map (see Text labels example) |
type SizeOption = "sm" | "md" | "lg" | "xl" | "xxl";
type ProjectionOption = "mercator" | "equalEarth";
type DataItem = {
country: ISOCode;
value: number | string;
};
type CountryContext = {
countryCode: ISOCode;
countryName: string;
countryValue: number | string | undefined;
color: string;
minValue: number;
maxValue: number;
prefix: string;
suffix: string;
dispute?: DisputeClassification; // Tier 1 dispute metadata, if any
};
type DisputedTerritoryContext = {
territoryId: string; // e.g. "crimea", "aksai-chin"
territoryName: string;
administration: string; // Natural Earth note, e.g. "Admin. by Russia; Claimed by Ukraine"
dispute: DisputeClassification; // includes status, parties, unStanding, sourceRationale
};
Zoom and pan
zoom is off by default. zoom (or zoom={true}) turns it on with the defaults below; pass an object to change them:
type ZoomOptions = {
enabled?: boolean; // default true when an object is passed
initialScale?: number; // default 1
minScale?: number; // default 1
maxScale?: number; // default 8
zoomFactor?: number; // zoom per button, key or double-click, default 2
showControls?: boolean; // zoom in / zoom out / reset buttons, default true
showCountryLabels?: boolean; // default true
countryLabelFormat?: "auto" | "long" | "short"; // "short": UN three-letter code (USA); "auto": name where it fits, else code; default "long"
showRegionLabels?: boolean; // region names, default false
regionLabelFormat?: "auto" | "long" | "short"; // default "auto": long where it fits, else short
showWater?: boolean; // ocean, sea and lake names, and the 100 largest lakes as water; default false
pinMinSize?: number; // pin size at zoom 1 as a share of full size, growing to full size at maxScale; default 1
pinCaptionMinScale?: number; // zoom level from which pin captions show (below it, overlapping markers are dropped unless keepOverlappingPins); default 1
keepOverlappingPins?: boolean; // keep overlapping pins and hide their clashing captions instead of dropping pins; default false
countryLabelMinFontSize?: number; // label size at 1x, in px, default 12
countryLabelMaxFontSize?: number; // default 20
countryLabelZoomGrowthRate?: number; // default 0.35
showPins?: boolean; // default true
detailedGeometry?: boolean; // load detailed borders when zoomed in, default true
detailedGeometryMinScale?: number; // default 2
regionDetailMinScale?: number; // zoom for detailLevel="regions", default 4
};
type ZoomState = {
scale: number; // 1 shows the whole map
translate: [number, number]; // offset of the map, in SVG pixels
};
type MapPin = {
id?: string;
coordinates: [longitude: number, latitude: number];
caption: string;
countryCode?: ISOCode; // written to data-country-code
kind?: string; // written to data-map-pin, default "pin"
color?: string; // this pin's marker colour; default the pinColor prop
shape?: "pin" | "square" | "diamond"; // marker head, so pins differ by more than colour; default "pin"
tooltip?: string; // tooltip on hover and focus; the pin then has a 24 px target, a Tab stop and this text as its name. Without it the pin ignores the pointer
priority?: number; // higher wins when pins overlap; default: earlier pins win
};
With zoom on:
- Buttons: zoom in, zoom out and reset, at the bottom right of the map.
- Pointer: drag to pan, double-click to zoom in around the pointer. A drag keeps going if the pointer leaves the map, and a drag that ends over a country doesn't click it.
- Wheel: hold ctrl (or ⌘) and scroll, or pinch on a trackpad, to zoom around the pointer. A plain wheel scrolls the page as usual, so the map never traps page scrolling.
- Keyboard (once the map has focus):
+/=zoom in,-/_zoom out, arrow keys pan,Escaperesets. The buttons come before the map in the tab order, and their hover hints name the keys. Countries and pins out of view leave the tab order. - Tooltips: they open on focus as on hover.
Escapecloses an open tooltip first; the nextEscaperesets the zoom. - The map always covers its viewport: you can't pan past its edges, with either projection.
- Zoom changes are announced to screen readers through a polite live region, with the zoom level ("Map zoomed in to 4x").
- Zooming and panning are animated, except while dragging and when the user prefers reduced motion (with or without zoom).
- Country borders keep a constant width while zooming (
vector-effect: non-scaling-stroke).
Country labels are drawn only where the name fits inside the country, larger countries first, at a constant on-screen size that grows slightly as you zoom in. Pins also keep their on-screen size.
onZoomChange is called from the interaction that changed the state, so you can store the state in your own component without causing a render loop:
const [zoomState, setZoomState] = useState<ZoomState>();
<WorldMap data={data} zoom={{ maxScale: 6 }} onZoomChange={setZoomState} />;
Without zoom, richInteraction behaves exactly as in earlier releases.
Detailed borders
With zoom, the map switches to detailed country borders (Natural Earth 10m) once zoomed in to detailedGeometryMinScale (default 2), and back to the default borders below it. The countries, their names and codes, and every callback stay the same; only the outlines get sharper. Disputed areas are assigned as in the default map; for example Crimea is part of Ukraine in both. See the Map Data Policy.
The detailed data comes in two levels, like map tiles. From zoom 2, the whole world, simplified (about 1.1 MB, 230 kB gzipped, dist/map-assets/countries-detailed.cjs). From zoom 16, each country in view at the full resolution of its source (dist/map-assets/countries-fine/XX.cjs, one file per country, 1 to 600 kB), fetched while the browser is idle one zoom step earlier. Each is loaded with import() the first time it is needed, so none is part of the default bundle and Vite and webpack emit each as its own chunk. With zoom, the map draws detailed borders only for the countries, and parts of countries, in view; the rest keep their light default outline. The map shows the default borders until it has loaded, and keeps them if it fails to load. Call preloadDetailedCountryGeometry() to load it ahead of time, or pass zoom={{ detailedGeometry: false }} to never load it. The countries layer has data-map-geometry="default" or "detailed" while zoom is on. Without zoom (including with richInteraction), the detailed data is never loaded.
Oceans, seas and lakes
zoom={{ showWater: true }} names the oceans and seas (with the larger gulfs, bays and straits) and the 100 largest lakes, and draws those lakes as water (the country borders include them as land). Labels are italic, in waterLabelColor, sized by kind (oceans largest), stay over water (a name of three or more words that would reach land is split over two lines, never three, an ocean name may shrink to a third of its size, and a label that still doesn't fit is dropped), and never overlap a country label; smaller seas appear as you zoom in, and a lake is named only where its name fits inside it. The data (about 350 kB, 95 kB gzipped) is a separate file, dist/map-assets/water.cjs, loaded with import() the first time it is needed. Names follow the map data policy.
Region detail
detailLevel="regions" draws the regions of the countries in view once zoomed in to regionDetailMinScale (default 4). The regions come from a detailProvider: the map asks it for each country in view that it supports: once per country for the same provider, or, for a provider with viewKey (below), again whenever the key for the view changes.
The optional react-svg-worldmap-regions package is a ready-made provider: states and provinces that have their own government (109 countries; every first-level division of 175 countries with createRegionsDetailProvider({ tier: "all" })), one lazily loaded file per country, so nothing downloads until the map is zoomed in on a country.
import { createRegionsDetailProvider } from "react-svg-worldmap-regions";
const regions = createRegionsDetailProvider(); // once, outside the component
<WorldMap data={data} zoom detailLevel="regions" detailProvider={regions} />;
You can also write your own provider. A provider with the optional viewKey is asked again, with the current view ({ scale, bounds: [[west, south], [east, north]] } in degrees), whenever the key it returns for a country changes, so it can load only the part in view and at a level of detail for the zoom; the map keeps the previous regions on screen until the new ones are ready. react-svg-worldmap-regions uses this to load a small file per country below zoom 8 and only the chunks in view above it.
type DetailProvider = {
supports: (countryCode: ISOCode) => boolean;
loadRegions: (
countryCode: ISOCode,
view?: DetailView, // only for a provider with viewKey
) => Promise<DetailProviderResult>;
viewKey?: (countryCode: ISOCode, view: DetailView) => string;
};
type DetailView = {
scale: number; // zoom level
bounds: [[number, number], [number, number]]; // [[west, south], [east, north]]; west > east across the antimeridian
};
type RegionFeature = {
id: string; // written to data-region-id
countryCode: ISOCode;
name: string; // written to data-region-name
shortName?: string; // shown when the name does not fit, such as "MA"
geometry: GeoJSON.Polygon | GeoJSON.MultiPolygon; // [longitude, latitude]
};
type RegionCollection = {
countryCode: ISOCode;
countryName?: string;
coverageStatus?: "complete" | "partial" | "experimental";
regions: RegionFeature[];
sourceSummary?: string;
sourceUrl?: string;
};
Region geometry is GeoJSON in [longitude, latitude] degrees, with the exterior ring clockwise (d3's winding, as produced by topojson-client). The map projects it with the current projection, so the same provider works with Mercator and Equal Earth. Return createReadyDetailResult(collection) when the regions are ready and createUnavailableDetailResult(countryCode) when there are none; a rejected promise is reported as failed.
const provider: DetailProvider = {
supports: (code) => code.toUpperCase() === "US",
loadRegions: async (code) => {
const collection = await fetchUsStates(); // your own data
return createReadyDetailResult(collection);
},
};
<WorldMap
data={data}
zoom
detailLevel="regions"
detailProvider={provider}
onDetailStatusChange={(status) => console.log(status.status)}
/>;
Region borders are dashed, in borderColor at the strokeOpacity of the countries, in the default and atlas themes (as in 2.x), and dotted in atlasLight. With zoom={{ showRegionLabels: true }}, region names are shown where they fit inside their region (9 to 12 px, regionLabelColor), below the country labels and never overlapping them. With the default regionLabelFormat: "auto", a region whose name does not fit shows its shortName (MA for Massachusetts) instead; "long" and "short" show only one of the two. They are in a <g data-map-sublayer="regions" class="worldmap__regions"> inside the countries layer (so the layer order numbers stay the same); style .worldmap__regions path with CSS to change them. onDetailStatusChange is called from the load itself, so storing the status in your component can't cause a render loop.