How do I add a dotted world map to a Next.js app?
Draw the map in a server component, any component of the App Router without 'use client', with @setkernel/dotted-map-next, and render its SVG string with dangerouslySetInnerHTML: the browser gets the SVG and none of the library. In a client component, draw a map precomputed by getMapJSON() with the small without-countries entry instead.
npm install @setkernel/dotted-map-next
A server component
A page of the App Router is a server component. This one has no dynamic
data, so next build renders it to static HTML, map included.
app/page.jsximport { DottedMap } from '@setkernel/dotted-map-next';
const map = new DottedMap({ height: 40 });
map.addPin({ lat: 37.7749, lng: -122.4194 });
const svg = map.getSVG({ title: 'San Francisco on a world map' });
export default function Page() {
return (
<main>
<div dangerouslySetInnerHTML={{ __html: svg }} />
</main>
);
}
app/page.jsx when this page was built.A client component
A client component runs in the browser too. Compute the map once with
getMapJSON() and draw it with the
without-countries entry, which holds no country data: with its
dependencies and the world at height: 60 it is 7,549 bytes
gzipped, against 43,525 bytes for the main entry. This one names the country
under the pointer, which needs the browser.
make-map.mjsimport { writeFileSync } from 'node:fs';
import { getMapJSON } from '@setkernel/dotted-map-next';
writeFileSync('app/world.json', getMapJSON({ height: 60 }));
app/WorldMap.jsx'use client';
import { useState } from 'react';
import { DottedMap } from '@setkernel/dotted-map-next/without-countries';
import world from './world.json' with { type: 'json' };
const svg = new DottedMap({ map: world }).getSVG({ title: 'World map' });
export function WorldMap() {
const [country, setCountry] = useState('');
const point = (event) =>
setCountry(event.target.closest('[data-country]')?.dataset.country ?? '');
return (
<figure>
<div onPointerOver={point} dangerouslySetInnerHTML={{ __html: svg }} />
<figcaption>{country || 'Point at a country'}</figcaption>
</figure>
);
}
make-map.mjs and app/WorldMap.jsx when this page was built.
Run node make-map.mjs again when you change the map's settings,
and render <WorldMap /> from any page.