Add Open Street Maps with Leaflet in React and also compatible with Next.js

Tiempo de lectura: 2 minutos

Today we are going to learn how we can create a map component compatible with Open Street Maps using the Leaflet library in React.

The first thing we need to do is install the necessary library:

npm install react react-dom leaflet

And then the Leaflet library:

npm install react-leaflet

And if we need TypeScript (in my case yes) we install the following:

npm install -D @types/leaflet

We install the icons:

npm install leaflet-defaulticon-compatibility

Now we can create a new component called Map.tsx

import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import "leaflet/dist/leaflet.css"
import "leaflet-defaulticon-compatibility"
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css"

//Define the data types that the component will receive in the form of an interface
interface Props {
    latitude: number;
    longitude: number;
}

function Map({ latitude, longitude }: Props) {
    return (
        
            
            
                
                   CSS3 popup, customizable
                
            
        
    );
}

export default Map;

Now we have created an example map, for it to work we will have to put:

<Map latitude={51.505} longitude={-0.09}/>

If we need it to be compatible with Next.js, we will have to use it in the following way:

  const DynamicMap = useMemo(() => dynamic(
    () => import('@/components/elements/Map'),
    {
      loading: () => <p>Loading...</p>,
      ssr: false
    }
  ), [])

We dynamically build the map by disabling Server Side Rendering.

And import the map like this:

<Map latitude={51.505} longitude={-0.09}/>

Leave a Comment