'react-leaflet map is not correcly displayed in Ionic 5

When i am trying to display map in mobile view i see broken map:

enter image description here

https://stackoverflow.com/a/36257493/13739566 - in this link is description why it doesn't work but use 'invalidSize()' doesn't work in my case (or maybe i use it wrong).It's my code:

import React from 'react';
import { IonContent, IonApp, IonHeader} from '@ionic/react';

import { Map as Maps, Marker, Popup, TileLayer, } from 'react-leaflet'

import 'leaflet/dist/leaflet.css'
import './MainTab.css';

const MainTab: React.FC = () => {

  return (
    <IonApp>
      <IonContent>
        <IonHeader>Header</IonHeader>

        <Maps center={position} zoom={13} keyboard={0} >

        <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
        <Marker position={position}>
    <Popup>Kliknij aby przejść do googla: </Popup>
    </Marker>
  </Maps>

        </IonContent>
  </IonApp>
  );
};

export default MainTab;


Solution 1:[1]

even using useEffect() I can't correct the map. So, I observed the onload() event.

import { Map, TileLayer, Marker } from 'react-leaflet';
import { LatLngTuple } from 'leaflet';

import 'leaflet/dist/leaflet.css';

const defaultLatLng: LatLngTuple = [-7.19207, -48.20779];
const zoom: number = 14;

const LeafletMap: React.FC = () => {

// ...

const refMap = useRef<Map>(null);

const startMap = useCallback(() => {
    refMap.current?.leafletElement.invalidateSize();
    setTimeout(() => {
      setLoading(false);
    }, 250);
  }, []);

  useEffect(() => {
    document.addEventListener('deviceready', startMap, false);
    window.addEventListener('load', startMap, false);
  });

// ...

<Map
  ref={refMap}
  center={defaultLatLng}
  zoom={zoom}
>
    <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    ></TileLayer>
</Map>

}

i haven't found a better way.

Solution 2:[2]

I add :

...
const mapRef = useRef(null)
useEffect(()=>{
      
      const map = mapRef.current.leafletElement; 
      map.invalidateSize()
     }
     )

And i used mapRef in ref in Maps and it's working for me

Solution 3:[3]

I had the same issue, it seems to be something async with Ionic view components and the map to renders "too early", I solved this by setting a slight delay for now.

const [ renderMap, setRenderMap ] = useState(false);

...

useLayoutEffect(() => {
    setTimeout(() => setRenderMap(true), 10);
  }, [])

...

 {renderMap && (
          <MapContainer
    ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 stawicz
Solution 3 Lindstrom