user2840647
user2840647

Reputation: 1314

ReactJS with Leaflet: tiles not correctly displayed until page refresh

I am building an application using Semantic UI and ReactJS. I am using a tab module to contain my map, which uses the Leaflet Javascript library to render the map.

The problem is that the tiles do not display correctly until the page is resized.

The is what I have tried:

MapComponent = React.createClass({
  componentDidMount() {
    let map = L.map('map')
    L.tileLayer.provider('Thunderforest.Outdoors').addTo(map)
    map.setView([lat, long], zoom)
    map.invalidateSize(false)
  }
}

Which did not seem to fix the problem.

I tried setting a timeout, like so:

MapComponent = React.createClass({
  componentDidMount() {
    let map = L.map('map')
    L.tileLayer.provider('Thunderforest.Outdoors').addTo(map)
    Meteor.setTimeout(() => {
      map.invalidateSize(false)
    }, 2000)
    map.setView([lat, long], zoom)
  }
})

Which sometimes worked by setting the timer to 2000, but sometimes it needed to be set to 5000, which is a bit crazy in my opinion.

From what I have read, calling the invalidateSize() function should fix the problem. Any help solving this problem would be greatly appreciated. Thank you.

Upvotes: 0

Views: 1590

Answers (1)

iH8
iH8

Reputation: 28688

Call invalidateSize once the tab containing your map becomes visible. In Semantic UI's tab module you can do that by using the onVisible callback:

Called after a tab becomes visible

http://semantic-ui.com/modules/tab.html#/settings

<div class="ui menu top">
    <a class="item" data-tab="map">Map</a>
</div>

$('.top.menu .item').tab({
    'onVisible': function () {
        // Do stuff
    }
});

Upvotes: 2

Related Questions