I'm using Next.js and their next/script component to load mapbox in a <Map /> component. This seems to work.
Map.js
import Script from 'next/script';
export default Map() {
const createMap = () => {
// set access token
mapboxgl.accessToken = 'xxxxxxxxxxxxxxx...';
// create map
const map = new mapboxgl.Map({...});
}
return (
<>
<Script
onLoad={() => {
createMap();
}}
src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"
/>
<div id="map"></div>
</>
);
}
1 - If I have multiple instances of <Map /> on a page, will Next.js load this script multiple times?
Is there a better way to load this script once, globally and synchronously? It doesn't seem to work if I load it in my _document.js page. Or is this not an issue?
2 - I also have to load the CSS file. Right now I have it loaded on the page that has the map on it.
pages/contact.js
import Head from 'next/head';
export default function PageContact() {
return (
<Head>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet" />
</Head>
);
}
If I add maps to other pages, I'd have to include this CSS file on all those other pages, resulting in a lot of duplication. Should I abstract this <Head> to its own component and include that on each page?
Or should I be moving this <Head> component into the <Map> component? It makes sense to centralize this style in one place, but at that point, just like the <Script>, I'm guessing Next.js would load the CSS file each time the component is instantiated, so if a page had more than one map on it, the CSS would be loaded multiple times.
What is the best way to load Mapbox in a Next.js project?