0

I need to invalidate some react-leaflet maps which are generated after the page loads with this code:

maps = [];
mapData = mapData.map(function(assetf,index){
    return(
      assetf.map(function(asset, index){
        var ind = index;
        var indHash = "#" + ind;
        var indExtra = ind + "ex";
        maps.push(indExtra);
        return(
          <li key={ind}>
            <div>{asset.description}</div>
            <Map id={indExtra} style={mapStyles} center={asset.point.coordinates} zoom={7}>
            <TileLayer
            url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />

            </Map>
          </li>
        )
      })
    )
  });

I tried using this code:

  var i;
  for(i=0; i < maps.length; i++){
      maps[i].invalidateSize(true);
  }

But this error is thrown:

Uncaught (in promise) TypeError: maps[i].invalidateSize is not a function

Thanks, Ed.

1 Answer 1

1

You are pushing map ID's into the array not Leaflet maps. That's why you can't call any Leaflet API functions(in your case it's invalidateSize) on just a string.

Instead of giving id to the map, give it a ref like:

<Map ref={indExtra} style={mapStyles} center={asset.point.coordinates} zoom={7}>

and then use the refs ids you store in the maps array to access the refs and invalidate them. Don't forget to use leafletElement as well.

 var i;
  for(i=0; i < maps.length; i++){
      this.refs[maps[i]].leafletElement.invalidateSize(true);
  }
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.