Problem whit sending my local position Leaflet

Viewed 24

When I'm initializing the const it's like that
-lat and leg are available only inside the function and when I'm send them to the map (I'm usinge Leaflet) it doesn't show them and it gave me that error:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

import {Component,useState,useEffect,useRef, ReactNode, CSSProperties, Link} from 'react';
import { MapContainer, TileLayer, Marker, Popup,useLeaflet,leafletElement} from 'react-leaflet'
function HomePage(){
  const [lat, setLat] = useState(null);
  const [lng, setLng] = useState(null);
  const [status, setStatus] = useState(null);
  if (!navigator.geolocation) {
      setStatus('Geolocation is not supported by your browser');
    } else {
      setStatus('Locating...');
      navigator.geolocation.getCurrentPosition((position) => {
        setStatus(null);
        setLat(position.coords.latitude);
        setLng(position.coords.longitude);
        console.log(lat,lng)
      }, () => {
        setStatus('Unable to retrieve your location');
      });
    }
    const position = [lat,lng]
return(
  <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <Marker position={position}>
      <Popup>
        A pretty CSS3 popup. <br /> Easily customizable.
      </Popup>
    </Marker>
  </MapContainer> 
)};
export default HomePage
1 Answers

Your component is re-rendering constantly. I'm not sure but I think below should work. You have to use useEffect hook and add a check on navigator at the start of component if(!navigator.geolocation) { return null; }

Related