Setting up a basic leaflets.js map in React

View Project

This demo project has been built with Create-React-App environment. To view it in browser

  • Fork and clone the repo
  • Run npm install from project root directory
  • Run npm start from project root directory screenshot

Leaflet Setup

To create a leaflet map in your own project:

  1. Install leaflet and react-leaflet with npm install react-leaflet leaflet.

  2. Import core components with import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet' and import { Icon } from 'leaflet' (see code in Map.js component).

  3. Add leaflet stylesheet to the component with import 'leaflet/dist/leaflet.css' (see code in Map.js component and leaflet.js docs).

  4. Add .leaflet-container class to css with map dimensions (other properties are optional). Note that the class does not have to be added anywhere in the Map component itself (see code in index.css).

.leaflet-container {
  width: 350px;
  height: 350px;
  1. Add MapContainer component inside a div with id="map" (see code in Map.js component and react leaflet docs).

 <div className="map" id="map" >
  <MapContainer center={position} zoom={6} scrollWheelZoom={true}>
      attribution='&copy; <a href="">OpenStreetMap</a> contributors'
    <Marker position={position}>

Note, I have defined the position as a variable inside the Map component but outside the return statement.

const position = [52.51, 13.38]


  1. Create a custom marker by defining a new instance of Icon outside the return statement. Note, there are additional properties that can be defined for the icon (see code in Map.js component)

const customIcon = new Icon({
    iconUrl: "/icons8-select-24.png",
    iconSize: [33, 33]

and add icon property to Marker component (see code in Map.js component).

<Marker position={position} icon={customIcon}>
  1. Add custom tiles by updating attribution and url properties in TileLayer component (see code in Map.js component).
  • You can find some tile options from leaflet extras. To update your project with one of the options simply copy attribution and url. For example, to include the Stadia.AlidadeSmoothDark map:

  attribution='&copy; <a href="">Stadia Maps</a>, &copy; <a href="">OpenMapTiles</a> &copy; <a href="">OpenStreetMap</a> contributors'

to learn about tiles with some entertainment value ??


View Github