Search code examples
reactjsleafletreact-leafletreact-leaflet-v4

react-leaflet basic example rendering


I'm using leaflet and react-leaflet for the first time and using their basic example here

and the map is broken in multiple sections with half not visible.

<MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.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>

The versions used are leaflet : 1.9.4 react-leaflet : 4.2.1 react : 18.2.0


Solution

  • You juste need to import leaflet CSS file and set the height and width of the MapContainer, the class name is leaflet-container

    // Component file
    import "leaflet/dist/leaflet.css"
    
    // CSS file
    .leaflet-container {
        height: 100vh;
        width: 100%;
    }
    

    don't forget to install leaflet package

    npm install leaflet