How to create web maps with Leaflet, React and functional components

How to create web maps with Leaflet, React and functional components

In this article I will explain how you can create a basic web map with Leaflet and React by using functional components without any third party packages. So i will strongly recommend to have a look at the Leaflet API reference.

React and Leaflet

First of all you need a react app which you can create with:

npx create-react-app leaflet-react
cd leaflet-react

Then you will need the Leaflet package which you can add with npm install leaflet or yarn add leaflet. After you have installed the package you can import it with import L from "leaflet" into your App.js. The import of the leaflet.css is also important because without it the map-tiles will be misplaced.

import React, { useEffect } from "react";
import L from "leaflet";
import 'leaflet/dist/leaflet.css';

const App = () => {
  
    return (
    )
  };
  
export default App;

Now you can create the actual map by using the UseEffect hook:

useEffect(() => {
  L.map("map", mapParams);
}, []);

The "map" parameter is the id of the html-element in which the map will be rendered. With mapParams you can passsome basic parameters as props for the Leaflet map. These parameters can just be created in a object Leaflet API: Map Creation):

const mapParams = {
  center: [0, 0],
  zoom: 0,
  layers: [layer]
};

TileLayers with OpenStreetMap Data can be created with L.tileLayer(url, options) (Leaflet API: TileLayer).

  const layer = L.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`, {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  });

Now you can create some basic css in js for the map container which makes the map fullscreen and will be passed as style props:

const mapStyles = {
  width: "100%",
  height: "100vh"
 };

In the end you just need html element in which the map will be rendered:

 return (
      <div>
        <div id="map" style={mapStyles} />
      </div>
    )

If you are curious how to add some more features like vector layers, some controls or markers have a look at the Leaflet API Reference and much fun playing around with your Leaflet web map created with React and functional components. In case something didn't work out as expected you can just clone the following repositiory.

Github Repositiory: https://github.com/dietrichmax/leaflet-react-functional-component Live Demo: https://dietrichmax.github.io/leaflet-react-functional-component/

All code together:

import React, { useEffect } from "react";
import L from "leaflet";
import 'leaflet/dist/leaflet.css';

const Map = () => {
    const mapStyles = {
        width: "100%",
        height: "100vh"
      };
      const layer = L.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`, {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      });
  

    const mapParams = {
      center: [0, 0],
      zoom: 0,
      layers: [layer]
    };
     
    // This useEffect hook runs when the component is first mounted, 
    // similar to componentDidMount() lifecycle method of class-based
    // components:
    useEffect(() => {
        L.map("map", mapParams);
    }, []);
  
    return (
      <div>
        <div id="map" style={mapStyles} />
      </div>
    )
  };
  
  export default Map;
js

About The Author

Max Dietrich
Max Dietrich

Geospatial Developer

Hi, I'm Max (he/him). I am a geospatial developer, author and cyclist from Rosenheim, Germany.

0 Webmentions

Have you published a response to this? Send me a webmention by letting me know the URL.

Found no Webmentions yet. Be the first!

Newsletter

Continue Reading

  • How to create a custom cookie banner for your React application

    Recently I implemented a custom cookie banner solution on my Next.js site which you probably have seen a few seconds before. There are a lot of prebuilt cookie banners you can use for React or Next js sites but i wanted to create a custom cookie banner which also has some personal touch and keeps the design with the website in line. Continue reading...
  • How to build a related posts component for your React blog

    Some blogs have these related articles or posts sections where visitors can have a preview at more content after they just read a post. That's what I wanted to create for my personal website which is built with React (Nextjs) and in this article I want to show you how you also can do it for any other react application. Continue reading...
  • How to deploy your Gatsby site on your own server

    With Gatsby 4 bringing in Server-Side Rendering (SSR) and Deferred Static Generation (DSG) you need an alternative methode to just hosting static files. Each page using SSR or DSG will be rendererd after a user requests it so there has be a server in the background which will handle these requests and build the pages if needed. Continue reading...