Reference Error: document is not defined in mapbox nextjs

Viewed 26

I installed @mapbox/search-js-react package for autocompletion in next js. It throws the document is not defined error.

I tried

{
     typeof window !== "undefined" && <PlacesSuggest />
}

Still not working. Could anyone help me to solve it?

1 Answers

First, why do you still get this error:

Your guard is not sufficient to prevent document is not defined:

The reference to document is evaluated before the guard: document is evaluated from the import of @mapbox/search-js-react which may be imported from PlagesSuggest.

You could use a dynamic import inside your guard but it will be easier to use NextJS features.

Use dynamic import with no ssr:

import dynamic from 'next/dynamic'

const PlacesSuggest = dynamic(() => import('./PlacesSuggest'), {
  ssr: false,
})

Related