React.js Leaflet-Usage and Installation

React Leaflet provides binding between Leaflet and React. The purpose of React Leaflet is not to replace Leaflet but to pull it to abstract Leaflet layers as React components. Leaflet is an interactive maps library written in JavaScript. React Leaflet has components for Leaflet maps. It does not render Leaflet layers to the DOM. It is done by Leaflet. React renders a <div> element when rendering the MapContainer component and the contents of UI layers components. To create needed Leaflet instances when the component is rendered the first time the properties are passed to components.They should be treated as immutable. When they change they will not be updated in the UI. React Leaflets uses React’s context API to make some Leaflet elements instances available to the children elements. Each Leaflet map instance has its React context. These React Context are created by the MapContainer component.Rest of the components, hooks provided by React leaflet can be used only as descendants of a MapContainer.  

The MapContainer calls a container <div> element for the map. Then MapContainer instantiates a Leaflet Map for created <div> with component properties and builds React context containing the map instance. MapContainer renders its children components, each child component instantiates the corresponding Leaflet instance for the element using the component properties and context and adds it to the map. When it is rendered again changes to its supported mutable props are applied to the map. When a component is rendered from the render tree it removes its layer from the map as required.

React Leaflets are not compatible with server-side rendering. To add React leaflet to your React application your system must contain React, React DOM and Leaflet. Then install React Leaflet using the following NPM/Yarn commands.

npm install react react-dom leaflet
npm install react-leaflet

Then import necessary components.

Eg:

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