Search code examples
javascriptreactjsleafletreact-leaflet

react leaflet basic tutorial map do not display map correctly


I follow react leaflet installation and got the setup page . They provide me a code snippet to use to see a basic example. However here is what I got. Not sure which steps did I mess up. enter image description here

import { GlobalStyle } from '../Theme';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import styled from 'styled-components';
import Header from '../components/Header';

const StyledLocationsPageContainer = styled.div`
    width: 100%;
    .leaflet-map-container {
        height: 25rem;
    }
`;

function Locations() {
    return (
        <StyledLocationsPageContainer>
            <GlobalStyle />
            <main>
                <Header />
                <div className="leaflet-map-container">
                    <MapContainer
                        center={[51.505, -0.09]}
                        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={[51.505, -0.09]}>
                            <Popup>
                                A pretty CSS3 popup. <br /> Easily customizable.
                            </Popup>
                        </Marker>
                    </MapContainer>
                </div>
            </main>
        </StyledLocationsPageContainer>
    );
}

export default Locations;


Here is my package .json file:

    "dependencies": {
        "@testing-library/jest-dom": "^5.11.9",
        "@testing-library/react": "^11.2.3",
        "@testing-library/user-event": "^12.6.0",
        "leaflet": "^1.7.1",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-leaflet": "^3.0.5",
        "react-scripts": "4.0.1",
        "styled-components": "^5.2.1",
        "web-vitals": "^0.2.4"
    }

After I insert the following link in the index.html, it just becomes empty white space with the width and height I assign to the wrapper div,

    <link
      rel="stylesheet"
      href="https://unpkg.com/[email protected]/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin=""
    />

Solution

  • You need to assign height to your MapContainer explicitly

     <MapContainer
           center={[51.505, -0.09]}
           zoom={13}
           scrollWheelZoom={false}
           style={{height: '100vh'}}> //here assign the height
    >
    ...
    

    and not to the wrapper of the MapContainer to be displayed as expected