Cannot read properties of null (reading 'offsetWidth') when loading react-leaflet map

774 Views Asked by At

I have a reusable leaflet map component in my react project and every time I search for a specific key word, the markers and the shapes(fences) will get updated. When I reload the parent component (initial data loads in the map and no issue) and search for the key word(2nd time map load), then if I click on the map it will give "Cannot read properties of null (reading 'offsetWidth') " . Can any one help me with this?

const MyComponent = ({ fences, markers}) => {    
let map;
let drawnItems = new L.FeatureGroup();

    useEffect(() => {
        initMap()
    }, [fences, markers]);

    function initMap() {
        let container = L.DomUtil.get('map');
        if (container != null) {
            container._leaflet_id = null;
        }
        document.getElementById('map').innerHTML = <div id='map' />;

        map = L.map('map', {
            drawControl: false
        }).setView([7.8731, 80.7718], 8);

 L.tileLayer(
            'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 18,
            }).addTo(map);

        map.addLayer(drawnItems);

      ...
      // Adding fences and markers to drawn items
      ...

    }
    return (
        <div id="map" />
    )
}
0

There are 0 best solutions below