react-leaflet icon indicating copy to clipboard operation
react-leaflet copied to clipboard

How how to add react-leaflet to a next-js app who is working with app routing

Open nelsonmandeladev opened this issue 1 year ago • 5 comments

Hi there, I'm trying without success to add react-leaflet to my next js 13.4.9 app with app routing and I'm getting this error : image

This is the component

image

nelsonmandeladev avatar Jul 15 '23 09:07 nelsonmandeladev

you should use dynamic import

tdvuanh avatar Jul 16 '23 08:07 tdvuanh

I have encountered this with NextJS before.

You can use dynamic import which @tdvuanh mentioned Refer to this documentation for more info: https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-no-ssr

It should be something like this:

'use client';
import dynamic from 'next/dynamic';

export const DynamicTestMap = dynamic(() => import('../components/TestMap'), {
  ssr: false,
});

export default DynamicTestMap ;

ivanaposdev avatar Aug 20 '23 13:08 ivanaposdev

Yet, I'm having this error in the browser:

Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server.

But the map is there...

And the marker is not present, just a squared frame :-(

ttsoares avatar Nov 20 '23 19:11 ttsoares

The hydration error is most likely caused by not deleting the normal import statement for the map.

So you probably have this:

'use client';
import dynamic from 'next/dynamic';
import TestMap from '../components/TestMap' // <-- DELETE this

export const DynamicTestMap = dynamic(() => import('../components/TestMap'), {
  ssr: false,
});

Instead of this:

'use client';
import dynamic from 'next/dynamic';

export const DynamicTestMap = dynamic(() => import('../components/TestMap'), {
  ssr: false,
});

The missing marker is a known issue when using leaflet with bundlers. There is an npm package that solves this problem: leaflet-defaulticon-compatibility.

Feel free to have a look at my stackoverflow post on how to setup react-leaflet 4 with nextjs 14.

ffrosch avatar Feb 15 '24 11:02 ffrosch

The dynamic import doesn't work for me. I receive an error Error: Map container is already initialized. This is the error's callstack:

Call Stack
NewClass._initContainer
node_modules/.pnpm/[email protected]/node_modules/leaflet/dist/leaflet-src.js (4207:1)
NewClass.initialize
node_modules/.pnpm/[email protected]/node_modules/leaflet/dist/leaflet-src.js (3249:1)
new NewClass
node_modules/.pnpm/[email protected]/node_modules/leaflet/dist/leaflet-src.js (302:1)
eval
node_modules/.pnpm/[email protected][email protected][email protected][email protected][email protected]/node_modules/react-leaflet/lib/MapContainer.js (30:1)

artilishes avatar Aug 14 '24 10:08 artilishes