Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next js with react-leaflet window is not defined when refreshing page

im using react-leaflet in Next js but when reloading page shows "window is not defined" even i am using dynamic import with ssr:false, i saw this question made by others here and tried answers that they offered but didn't work, also tried to make the map mounted after component but again no result, my code:

function ContactPage() {
    const MapWithNoSSR = dynamic(() => import('../Map/Map'), {
        ssr: false,
    })
    return (
        <div className={styles.map}>
            <MapWithNoSSR/>
        </div>
    )
}

function Map(){

const [markers, setMarkers]= useState([
        {cord:[12.3774729,20.446257]},
        {cord:[45.3774729,10.45224757]},
        {cord:[40.3774729,15.4364757]},
    ])

<MapContainer center={[12.374729,22.4464757]} zoom={13} scrollWheelZoom={true} style={{height: "100%", width: "100%",zIndex:'1'}}>
          <TileLayer
              url={`example.com`}
              attribution='Map data &copy; <a>Mapbox</a>'
          />
          {markers?.map((element,idx)=>{
            return <Marker
                position={element?.cord}
                draggable={true}
                animate={true}
                key={idx}
            >
              <Popup>
                Test PopUP
              </Popup>
            </Marker>
          })}
        </MapContainer> 

}}
}
like image 247
Riks1 Avatar asked Dec 07 '25 07:12

Riks1


1 Answers

as you were told in the comment, dynamic () has to go outside of the component or screen you are going to return, e. g.

import dynamic from "next/dynamic"

const MyAwesomeMap = dynamic(() => import("../components/Map/index"), { ssr:false })

export default function inicio() {

return(
 <>
  <p>Example Map</p>
  <MyAwesomeMap />
 </>
 )
}
like image 162
fabianmeneses Avatar answered Dec 08 '25 21:12

fabianmeneses



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!