Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

187
Vistas
React-Leaflet: Cannot display leaflet map properly after toggling by using functional component

When I click the button "Search heritage", I want to display the map on my webpage. However, the Leaflet Map cannot show properly as below:

Webpage display

The map can be fully displayed without any problem once I resize my webpage. I have found some solutions that can solve this problem based on class component but I have no idea to solve it when using functional component.

Here is my current code.

  1. leaflet.tsx

import "./leaflet.css";

import { MapContainer, TileLayer, useMap, Popup, Marker } from "react-leaflet";

export default function Leaflet() {
  const mapRef: any = createRef();

  useEffect(() => {
    const map = mapRef.leafletElement;
    setTimeout(() => {
      map.invalidateSize();
    }, 1000);
  }, [mapRef]);

  return (
    <div className="map">
      <MapContainer
        center={[22.3193, 114.1694]}
        zoom={10}
        scrollWheelZoom={false}
        ref={mapRef}
      >
        <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={[50.5, 30.5]}>
          <Popup></Popup>
        </Marker>
      </MapContainer>
    </div>
  );
}

2.leaflet.css

  font-family: sans-serif;
  text-align: center;
}

.leaflet-container {
  height: 600px;
  width: 100%;
}

.leaflet-div-icon {
  background: transparent;
  border: none;
}

I am using react-leaflet ^4.0.0

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos