Reputation: 107
I included leaflet map with js
implementation instead of jsx
implementation but I have a problem as it overflows its scope.
this is how I imported leaflet:
import L from 'leaflet';
and implemented:
componentDidMount() {
// create map
this.map = L.map('map', {
center: [49.8419, 24.0315],
zoom: 16,
layers: [
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}),
]
});
}
and usage:
<div id={"map"} >
Upvotes: 0
Views: 4313
Reputation: 9713
You have not added the leaflet css file in your index.html
.
For leaflet version 1.3.4
, add the following to index.html
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
In your map component css file, override the leaflet-container
class with desired height and width.
.leaflet-container {
height: 600px;
width: 100%;
}
Once you have added that, use Map
and TileLayer
Components of react-leaflet
to render map.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer } from "react-leaflet";
import "./styles.css";
class App extends Component {
state = {
center: [51.505, -0.091],
zoom: 13
};
render() {
return (
<div>
<Map center={this.state.center} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
</Map>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can find working code here. https://codesandbox.io/s/2wnv7o1mlr
Upvotes: 4
Reputation: 1042
Yeah you're missing the css file.
incidentally this is not how you should be using react-leaflet
.
componentDidMount is not the place for doing what you're doing. Put that in the render like
import { Map, TileLayer } from 'react-leaflet';
<Map>
<TileLayer url="'http://{s}.tile.osm.org/{z}/{x}/{y}.png'" />
</Map>
Upvotes: 0