title: React leaflet map location glitches when not in App.js
body: <p>I am trying to use a Leaflet map in my React application but I am running into a strange problem. I tell my map to pan to the user's current geolocation (if they have allowed access to their location) in the whenReady function but when it does that the map glitches out. What makes this weirder is that it only happens when I put my map in a view where I route to from App.js (I want to display it together with a navigation bar). When it is in App.js itself, this doesn't occur and the map displays correctly with my location. I attached pictures to show what I mean:</p>
  <p>When the map is in App.js:
  <a href="https://i.stack.imgur.com/jk2bb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jk2bb.png" alt="The map displays correctly with the pin in the center" /></a></p>
  <p>When the map is in another component:
  <a href="https://i.stack.imgur.com/mzeKQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mzeKQ.png" alt="The map is entirely grey with the pin out of the center" /></a></p>
  <p>Here is my code for the two situations:</p>
  <p>Code when the map is in App.js:</p>
  <pre><code>import React, {Component} from 'react';
  import L from 'leaflet';
  import './MapView.css';
  import fence from './assets/fence.png';
  import pin from './assets/pin.png';
  import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
  
  class App extends Component {
    constructor() {
      super();
      this.state = {
        markers: [],
        center: [51.505, -0.09]
      };
      this.addMarker = this.addMarker.bind(this)
    }
  
    fence = L.icon({
      iconUrl: fence,
      iconSize:     [46.3125, 51.5625], // size of the icon
      iconAnchor:   [22, 25], // point of the icon which will correspond to marker's location
      popupAnchor:  [0, -25]
    });
    
    addMarker = (e) =&gt; {
      const {markers} = this.state
      markers.push(this.state.center)
      this.setState({markers})
    }
  
    render() {
      const self = this;
      return (
        &lt;div className=&quot;map-container&quot;&gt;
          &lt;button onClick={this.addMarker} className=&quot;btn&quot;&gt;+&lt;/button&gt;
          &lt;div className=&quot;center&quot;&gt;&lt;/div&gt;
        &lt;MapContainer 
          className=&quot;map&quot;
          minZoom= {8}
          zoom={20} 
          center = {this.state.center}
          whenReady={(map) =&gt; {
            if ('geolocation' in navigator) {
              navigator.geolocation.getCurrentPosition(function (location) {
                console.log(location);
                map.target.panTo(new L.LatLng(location.coords.latitude, location.coords.longitude))
  
                var marker = L.marker([location.coords.latitude, location.coords.longitude], {icon: L.icon({
                  iconUrl: pin,
                  iconSize:     [24, 38], // size of the icon
                  iconAnchor:   [12.5, 40], // point of the icon which will correspond to marker's location
                  popupAnchor:  [0, -50]
                })} ).addTo(map.target);
                marker.bindPopup(&quot;Your current location&quot;)
                marker.openPopup()
              });
            }
  
            map.target.on(&quot;drag&quot;, function (e) {
              self.setState({center: map.target.getCenter()})
            });
  
            map.target.on(&quot;zoom&quot;, function (e) {
              self.setState({center: map.target.getCenter()})
            })
          }}
          &gt;
          &lt;TileLayer
            attribution='&amp;copy; &lt;a href=&quot;http://osm.org/copyright&quot;&gt;OpenStreetMap&lt;/a&gt; contributors'
            url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
          &gt;&lt;/TileLayer&gt;
          {this.state.markers.map((position, idx) =&gt; 
            &lt;Marker key={`marker-${idx}`} icon={this.fence} position={position}&gt;
            &lt;Popup&gt;
              &lt;span&gt;Title&lt;br/&gt;&lt;/span&gt;
            &lt;/Popup&gt;
          &lt;/Marker&gt;
          )}
        &lt;/MapContainer&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default App;
  </code></pre>
  <p>Code when the map is in another view, routed from App.js:</p>
  <pre><code>//App.js
  import React from &quot;react&quot;;
  import &quot;./App.css&quot;;
  import { BrowserRouter as Router, Switch, Route } from &quot;react-router-dom&quot;;
  import MapView from './MapView';
  import AddView from './AddView';
  import Navbar from './Navbar';
  
  function App() {
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;Router&gt;
        &lt;Navbar/&gt;
          &lt;Switch&gt;
            &lt;Route exact from=&quot;/&quot; component={MapView} /&gt;
            &lt;Route exact path=&quot;/new&quot; component={AddView} /&gt;
          &lt;/Switch&gt;
        &lt;/Router&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  
  //MapView.js
  import React, {Component} from 'react';
  import L from 'leaflet';
  import './MapView.css';
  import fence from './assets/fence.png';
  import pin from './assets/pin.png';
  import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
  
  class MapView extends Component {
    constructor() {
      super();
      this.state = {
        markers: [],
        center: [51.505, -0.09]
      };
      this.addMarker = this.addMarker.bind(this)
    }
  
    fence = L.icon({
      iconUrl: fence,
      iconSize:     [46.3125, 51.5625], // size of the icon
      iconAnchor:   [22, 25], // point of the icon which will correspond to marker's location
      popupAnchor:  [0, -25]
    });
    
    addMarker = (e) =&gt; {
      const {markers} = this.state
      markers.push(this.state.center)
      this.setState({markers})
    }
  
    render() {
      const self = this;
      return (
        &lt;div className=&quot;map-container&quot;&gt;
          &lt;button onClick={this.addMarker} className=&quot;btn&quot;&gt;+&lt;/button&gt;
          &lt;div className=&quot;center&quot;&gt;&lt;/div&gt;
        &lt;MapContainer 
          id=&quot;map&quot;
          className=&quot;map&quot;
          minZoom= {8}
          zoom={20} 
          center = {this.state.center}
          whenReady={(map) =&gt; {
              if ('geolocation' in navigator) {
                navigator.geolocation.getCurrentPosition(function (location) {
                  localStorage.setItem('latitude', location.coords.latitude)
                  localStorage.setItem('longitude', location.coords.longitude)
                  let latitude= location.coords.latitude;
                  let longitude= location.coords.longitude;
                  console.log(location);
  
                  map.target.panTo(new L.LatLng(latitude, longitude))
    
                  var marker = L.marker([latitude, longitude], {icon: L.icon({
                    iconUrl: pin,
                    iconSize:     [24, 38], 
                    iconAnchor:   [12.5, 40], 
                    popupAnchor:  [0, -50]
                  })} ).addTo(map.target);
                  marker.bindPopup(&quot;Your current location&quot;)
                  marker.openPopup()
                });
              } else {
                  console.log(&quot;Ik kom erin bro wtf&quot;)
                  let latitude = localStorage.getItem('latitude') ?? 51.505
                  let longitude = localStorage.getItem('longitude') ?? -0.09
  
                  map.target.panTo(new L.LatLng(latitude, longitude))
              }
    
              map.target.on(&quot;drag&quot;, function (e) {
                self.setState({center: map.target.getCenter()})
              });
    
              map.target.on(&quot;zoom&quot;, function (e) {
                self.setState({center: map.target.getCenter()})
              })
            }}
          &gt;
          &lt;TileLayer
            attribution='&amp;copy; &lt;a href=&quot;http://osm.org/copyright&quot;&gt;OpenStreetMap&lt;/a&gt; contributors'
            url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
          &gt;&lt;/TileLayer&gt;
          {this.state.markers.map((position, idx) =&gt; 
            &lt;Marker key={`marker-${idx}`} icon={this.fence} position={position}&gt;
            &lt;Popup&gt;
              &lt;span&gt;Title&lt;br/&gt;&lt;/span&gt;
            &lt;/Popup&gt;
          &lt;/Marker&gt;
          )}
        &lt;/MapContainer&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default MapView;
  
  //Navbar.js
  import { makeStyles } from '@material-ui/core/styles';
  import AppBar from '@material-ui/core/AppBar';
  import Toolbar from '@material-ui/core/Toolbar';
  import Typography from '@material-ui/core/Typography';
  import Button from '@material-ui/core/Button';
  import IconButton from '@material-ui/core/IconButton';
  import MenuIcon from '@material-ui/icons/Menu';
  import {
      Link
    } from &quot;react-router-dom&quot;;
  
  
  const useStyles = makeStyles((theme) =&gt; ({
      root: {
        flexGrow: 1,
      },
      menuButton: {
        marginRight: theme.spacing(2),
      },
      title: {
        flexGrow: 1,
      },
      bar: {
          height: '7.5vh',
      }
    }));
  
  function Navbar() {
      const classes = useStyles();
  
      return (
          &lt;AppBar position=&quot;static&quot; className={classes.bar}&gt;
          &lt;Toolbar&gt;
            &lt;IconButton edge=&quot;start&quot; className={classes.menuButton} color=&quot;inherit&quot; aria-label=&quot;menu&quot;&gt;
              &lt;MenuIcon /&gt;
            &lt;/IconButton&gt;
            &lt;Typography variant=&quot;h6&quot; className={classes.title}&gt;
              Work in progress
            &lt;/Typography&gt;
            &lt;Link color=&quot;inherit&quot; to=&quot;/new&quot;&gt;Report construction&lt;/Link&gt;
            &lt;Button color=&quot;inherit&quot;&gt;Login&lt;/Button&gt;
          &lt;/Toolbar&gt;
        &lt;/AppBar&gt;
      );
    }
    
    export default Navbar;
  </code></pre>
  <p>I don't have too much knowledge in Leaflet, because this is the first app I make with it, so please take this into consideration if I am confusing some theory behind this. Does anybody know if there is something wrong with my code, my way of thinking, or if there is some Leaflet theory behind this that I am missing? I look forward to hearing any answers.</p>