How do I make a dotted world map in React?
Draw the map with @setkernel/dotted-map-next, whose getSVG() returns an SVG string, and render that string with <div dangerouslySetInnerHTML={{ __html: svg }} />. The string is safe to insert: the library escapes every text it writes and throws on a colour or a number it cannot draw.
npm install @setkernel/dotted-map-next
The component
The map is drawn once, when the module loads, and every render of
WorldMap uses the same string.
WorldMap.jsximport { DottedMap } from '@setkernel/dotted-map-next';
const map = new DottedMap({ height: 40 });
map.addPin({ lat: 35.6762, lng: 139.6503 });
const svg = map.getSVG({ title: 'Tokyo on a world map' });
export function WorldMap() {
return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}
WorldMap.jsx when this page was built.A server component
WorldMap has no state, no effects and no event handlers, so in a
React Server Components framework, such as the Next.js App Router, it is a
server component as it is: the server sends the SVG in the HTML, and the
browser downloads none of the library. A server component can draw a map for
its props on each render, as PinMap does; after the first map,
the grid of a given height comes from the library's cache.
PinMap.jsximport { DottedMap } from '@setkernel/dotted-map-next';
export function PinMap({ pins, title }) {
const map = new DottedMap({ height: 40 });
for (const pin of pins) map.addPin(pin);
const svg = map.getSVG({ title });
return <div dangerouslySetInnerHTML={{ __html: svg }} />;
}
Use it as
<PinMap pins={[{ lat: 48.8566, lng: 2.3522 }]} title="Paris" />.
In the browser
In a client component the library runs in the browser: the main entry with
its dependencies is 43,525 bytes gzipped. A map precomputed at build time
and drawn with the without-countries entry is 7,549 bytes, as
the Next.js page shows.