DEV Community

Cover image for A friendly guide to using react-leaflet with React
Leandro Nuñez for Digital Pollution

Posted on • Updated on

A friendly guide to using react-leaflet with React

Hello there!

Welcome to our friendly guide on how to use the latest versions of React and React-Leaflet to create awesome interactive maps.

We'll walk you through the steps, provide code examples, and sprinkle in some tips along the way.

Let's get started!

Table of Contents:

  1. Installing Dependencies
  2. Creating a Basic Map Component
  3. Adding Markers and Popups
  4. Customizing the Map
  5. Interactivity and Events
  6. Using React-Leaflet Plugins
  7. Tips and Best Practices

1. Installing Dependencies:

Let's start by making sure you have Node.js and npm (or Yarn) installed.

Once you're all set, create a new React project using create-react-app and install the required packages:

Using npm:

npx create-react-app react-leaflet-demo
cd react-leaflet-demo
npm install react-leaflet leaflet
Enter fullscreen mode Exit fullscreen mode

Using Yarn:

npx create-react-app react-leaflet-demo
cd react-leaflet-demo
yarn add react-leaflet leaflet
Enter fullscreen mode Exit fullscreen mode

2. Creating a Basic Map Component:

Now, it's time to create a simple map component that displays a map with a specified center and zoom level.

The MapContainer and TileLayer components will do the magic:

import React from 'react';
import { MapContainer, TileLayer } from 'react-leaflet';

const Map = () => {
  return (
    <MapContainer center={[latitude, longitude]} zoom={13} style={{ height: '500px' }}>
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
    </MapContainer>
  );
};

export default Map;
Enter fullscreen mode Exit fullscreen mode

3. Adding Markers and Popups:

Make your map more engaging by adding markers and popups!

Check out how simple it is using React-Leaflet's Marker and Popup components:

import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

const Map = () => {
  return (
    <MapContainer center={[latitude, longitude]} zoom={13} style={{ height: '500px' }}>
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <Marker position={[markerLat, markerLng]}>
        <Popup>
          A popup message on the marker.
        </Popup>
      </Marker>
    </MapContainer>
  );
};

export default Map;
Enter fullscreen mode Exit fullscreen mode

4. Customizing the Map:

Let your creativity shine by customizing the map's appearance and behavior.

You can easily pass options to the MapContainer component:

import React from 'react';
import { MapContainer, TileLayer } from 'react-leaflet';

const Map = () => {
  const mapOptions = {
    center: [latitude, longitude],
    zoom: 13,
    maxZoom: 18,
    minZoom: 5,
  };

  return (
    <MapContainer {...mapOptions} style={{ height: '500px' }}>
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
    </MapContainer>
  );
};

export default Map;
Enter fullscreen mode Exit fullscreen mode

5. Interactivity and Events:

Make your map more interactive!

React-Leaflet provides various events for you to handle, like click events on the map and display coordinates:

import React from 'react';
import { MapContainer, TileLayer, useMapEvents } from 'react-leaflet';

const Map = () => {
  const handleMapClick = (e) => {
    const { lat, lng } = e.latlng;
    alert(`Clicked at: ${lat}, ${lng}`);
  };

  return (
    <MapContainer center={[latitude, longitude]} zoom={13} style={{ height: '500px' }}>
      <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
      <MapEventsHandler handleMapClick={handleMapClick} />
    </MapContainer>
  );
};

const MapEventsHandler = ({ handleMapClick }) => {
  useMapEvents({
    click: (e) => handleMapClick(e),
  });
  return null;
};

export default Map;
Enter fullscreen mode Exit fullscreen mode

6. Using React-Leaflet Plugins:

Enhance your maps with the vast array of React-Leaflet plugins available.

Discover and integrate the ones that suit your project's needs.

As a personal recommendation, I give you this package that is great for managing large data in your map: react-leaflet-cluster.

For more details, check out the official documentation.

7. Tips and Best Practices:

  • Keep your map components modular and reusable for better code maintainability.
  • Optimize map rendering and data fetching to provide a smooth user experience.
  • Always use the latest versions of React and React-Leaflet for improved performance and security.

Now that you've gone through this guide, you should be well-equipped to create captivating maps with React-Leaflet in your React projects.

Have fun mapping!

Top comments (1)

Collapse
 
javlonbk profile image
Javlonbek

codesandbox.io/p/github/Javlonbk/r...

Hello, I had a question about this map. In the map file, the map is brought online. and change this map offline in the public folder. This should be done offline, that is, from a local file. I have a problem. If anyone could help it would be greatly appreciated. This part of the big project bit is the problem.