Today we are going to learn how we can create a map component compatible with Open Street Maps using the Leaflet library in React.
![](https://i0.wp.com/images.pexels.com/photos/2026324/pexels-photo-2026324.jpeg?w=1200&ssl=1)
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}/>
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2024/03/imagen-17.png?resize=713%2C220&ssl=1)
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1)