How to Include "Leaflet.CSS" in a React App with Webpack

react-leaflet map not correctly displayed

Looks like you haven't loaded in the Leaflet stylesheet.

From the react-leaflet GitHub guide:

If you are not familiar with Leaflet, make sure you read its quick start guide before using this library.
You will notably need to add its CSS to your page to render the map properly, and set the height of the container.

http://leafletjs.com/examples/quick-start/

Here is what you'll need:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.1/dist/leaflet.css" />

Update

Note @ThomasThiebaud indicates you may also have to set up the height of .leaflet-container

--

Ange Loron also gave a correct, optional, JS module import (vs cdn or style link)

import 'leaflet/dist/leaflet.css';




For what its worth, the documentation page is poorly designed... and the maintainer continuously deals with this issue in GitHub, but for some reason, the issue is the *fault of the users who continuously don't do the required setup. /s

Leaflet map partially loading within React project

  1. You did forget to include Leaflet CSS file.
  2. You incorrectly specify your .map container height.

1. Include Leaflet CSS

Pay attention to how the working example you mention in your comment imports Leaflet assets (in Map/leaflet.js file):

import L from 'leaflet'; // Same as `import * as L from 'leaflet'` with webpack
import 'leaflet/dist/leaflet.css';

Notice that it imports Leaflet CSS file explicitly. When it is missing, your tiles will appear shuffled and spread over your page.

Webpack has a style-loader and css-loader to correctly manage these CSS assets when they are referred to in a JS file.

2. Specify the map container height

In your failing code sample, you specify your <div class="map"> container with CSS:

.map {
height: 100%;
}

Be aware that percentage value is based on the element's parent node value, i.e. in this case 100% of the parent's height.

Your DOM hierarchy is:

<html>
<body>
<div id="root">
<div class="App">
<div class="map">

But you have not specified any height for any of your map container's ancestors (i.e. html, body, #root and .App). Since their only child is .map, they do not have anything else to increase their size, hence they have 0 height.

And your .map's height is 100% of 0, i.e. 0.

Make sure you also specify a height value for each of these ancestors:

html,
body,
#root,
.App {
margin: 0;
height: 100%;
}

Or use an explicit height value for your map container, e.g. in px.

Updated CodeSandbox: https://codesandbox.io/s/zn89pkmn83



Related Topics



Leave a reply



Submit