Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
The Center in a MapContainer in React-Leaflet-js Won't Update

I've started to use React.js lately and was working on a project using React-Leaflet-js. My problem is that my MapContainer doesn't change the center of the page whenever the position variable in the following code is updated:

...
  render() {
    const position = [this.state.location.lat, this.state.location.lng];
    return (
      <MapContainer
      className="map"
      center={position}
      zoom={this.state.zoom}
      scrollWheelZoom={true}>
...

For reference, the state variable that is being updated looks like this:

    state = {
    location: {
      lat: 40.7128,
      lng: -74.0060,
    },
    haveUsersLocation: false,
    zoom: 13,
  }

What's weird is that a marker with a position set to {position} will automatically update when the position variable changes but not the center of the MapContainer. I'm not sure why the map doesn't respond and adjust its center.

Note: I tried looking at this but it didn't answer my question. Please help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The center property just initialize the map, if you want to update the center of the map actually shown you have to use either setView or flyTo if you want a smooth animation. In order to get a Leaflet Map reference you need to use the hook useMap.

function FlyMapTo() {

    const map = useMap()

    useEffect(() => {
        map.flyTo(position)
    }, [position])

    return null
}

return (
<MapContainer
      className="map"
      center={position}
      zoom={this.state.zoom}
      scrollWheelZoom={true}>
    <FlyMapTo />
</MapContainer>
)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!