How to use leaflet in react js

Spread the love

Using Leaflet in a React application is a straightforward process. Leaflet is a powerful open-source JavaScript library for interactive maps, and integrating it with React can be done efficiently using the react-leaflet library, which provides React components for Leaflet maps. Here’s a step-by-step guide to get you started:

1. Set Up Your React Project

First, make sure you have a React project set up. If you don’t already have one, you can create one using Create React App:

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

2. Install Leaflet and React-Leaflet

Next, you need to install both leaflet and react-leaflet:

npm install leaflet react-leaflet

3. Add Leaflet CSS

Leaflet requires some CSS to display the maps correctly. Add the following CSS import to your index.js or App.js file:

import 'leaflet/dist/leaflet.css';

4. Create a Map Component

Now, create a new component, MapComponent.js, to render your Leaflet map:

// src/MapComponent.js
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

const MapComponent = () => {
const position = [51.505, -0.09]; // Coordinates for the map center

return (
<MapContainer center={position} zoom={13} style={{ height: "100vh", width: "100%" }}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
};

export default MapComponent;

5. Use Your Map Component

Finally, use your MapComponent in your main App.js file:

// src/App.js
import React from 'react';
import './App.css';
import MapComponent from './MapComponent';

function App() {
return (
<div className="App">
<MapComponent />
</div>
);
}

export default App;

6. Run Your Application

Start your React application:

npm start

You should now see a Leaflet map rendered in your browser.

1 thought on “How to use leaflet in react js”

Comments are closed.

Scroll to Top