How to use leaflet map with React

Using the maps for showing locations, markers and popups is very common for big projects. Whenever any developer needs map in there project they usually have two options i.e Google Maps and Leaflet. In this article we will gonna learn how to use leaflet map with React.

What is leaflet ?

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 38 KB of JS, it has all the mapping features most developers ever need.

Leaflet is designed with simplicity, performance and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple.

How to use leaflet with React ?

We have multiple ways to use Leaflet with React. We can use script tag to get leaflet functionality and we can also use npm package. For this article we will gonna use npm package.

React-leaflet

Installation

Like any other package first of all we need to install this package.

npm install react-leaflet

Usage

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

const position = [51.505, -0.09];
const map = (
  <Map center={position} zoom={13}>
    <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
    />
    <Marker position={position}>
      <Popup>A pretty CSS3 popup.<br />Easily customizable.</Popup>
    </Marker>
  </Map>
)

What we did in above example we just imported Map for map container, Marker for showing the marker on the map, Popup which will be gonna open on click of marker, TileLayer for map background.

Demo

You will get output like this.

How to use leaflet map with React

Pagination with Limit and Skip is slower

Categories: Reactjs