Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
How do I load mapbox in Next.js?

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda