Skip to content

Instantly share code, notes, and snippets.

@ManishPoduval
Last active March 17, 2022 17:02
Show Gist options
  • Save ManishPoduval/3a2a412c91e8bb18841799f69e3777c5 to your computer and use it in GitHub Desktop.
Save ManishPoduval/3a2a412c91e8bb18841799f69e3777c5 to your computer and use it in GitHub Desktop.

Maps in React

1. Install package

We will use this package to show a map on our site

In your React code terminal run

npm i react-leaflet leaflet

2. Set up Component

Create a component called MyMap

import React from  'react'
import {MapContainer, TileLayer, Marker, Popup} from  'react-leaflet'
//Don't forget to import the css
import  'leaflet/dist/leaflet.css'

  
function MyMap() {
    //Some random co-ordinate
	const position = [51.505, -0.09]

    //Do not forget to set a width and height style to your map. Else it won't show up
	return (
	<div>
		<MapContainer  
			style={{width: '800px', height: '500px'}} 
			center={position}  zoom={13}  
			scrollWheelZoom={false}>
			<TileLayer
				attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
				url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
			/>
			<Marker  position={position}>
				<Popup>
					A pretty CSS3 popup. <br  /> Easily customizable.
				</Popup>
			</Marker>
		</MapContainer>
	</div>
	)
}

export  default MyMap

Do you get this error ?

enter image description here

That's happening because the most recent version of react-leaflet is using some recent JS functionalities like the null coalescing ?? which babel does not understand. To fix this, in your package.json update the part of browserslist

from

"browserslist": {
	"production": [
		">0.2%",
		"not dead",
		"not op_mini all"
	],
	"development": [
		"last 1 chrome version",
		"last 1 firefox version",
		"last 1 safari version"
	]
},

to

"browserslist": [
	">0.2%",
	"not dead",
	"not op_mini all"
],

Then delete your node_modules folder, run npm install again and start your app

3. Custom Icons

To show custom icons, use the leaflet library

import L from  'leaflet';

Create a simple leaflet icon with your own custom Image

We will use Ironhack's logo here

const ironhackLogo = new L.Icon({
	iconUrl: 'https://i1.wp.com/www.alliron.vc/wp-content/uploads/2018/05/logo-ironhack-1.png',
	iconSize: [68, 65],
});

Pass the 'icon' prop to the Marker component

<Marker icon={ironhackLogo} />

Happy coding! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment