DEV Community

Cover image for Guide to React leaflet
Asm Raihan
Asm Raihan

Posted on

Guide to React leaflet

React Leaflet provides bindings between React and Leaflet. It uses Leaflet to abstract Leaflet layers and turn them into React components, not replacing Leaflet.

React-leaflet is very easy to implement. But the official documentation is a little vague to me. So here are we,

STEP - 1 // Installing React-Leaflet as dependency

npm install react-leaflet

yarn add react-leaflet

STEP - 2 // Importing components

All the components and hooks can be imported from the module entry-point:

import { MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
Enter fullscreen mode Exit fullscreen mode

For TypeScript only

yarn add -D @types/leaflet
Enter fullscreen mode Exit fullscreen mode

STEP - 3 // Creating map component

<MapContainer center={[38.706928957217166, 35.51448175987359]} zoom={13} scrollWheelZoom={true}>
                <TileLayer

                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={[38.706928957217166, 35.51448175987359]}>
                    <Popup>
                        popup <br /> message.
                    </Popup>
                </Marker>
            </MapContainer>
Enter fullscreen mode Exit fullscreen mode

STEP - 4 // Adding CSS style to show map properly

  .leaflet-container{
    width: 100vw;
    height: 100vh ;
  }
Enter fullscreen mode Exit fullscreen mode

You are all set. This is the basic usage of leaflet. See the official documentation for more customization. Have fun!
https://www.npmjs.com/package/react-leaflet
https://react-leaflet.js.org/docs/start-installation/
https://leafletjs.com/
https://github.com/PaulLeCam/react-leaflet

Top comments (0)