Skip to content

React Leaflet Bound not working as expected

I’m using react-leaflet package to create bound animation on the map from selected markers as seen on the screenshot below.

enter image description here

Here is the full code:

The map will be bound if only the selected markers change.

I try to implement the bound animation sample code from the documentation here

As we can see from the screenshot above, the map, the markers, the rectangle, and the panel (top-right corner) are displaying and working fine.

But if we change the selected markers (through the panel), the bound animation is not working properly (not showing all of the markers).

And if we empty the selected markers (no marker is selected in the panel), the app crashes and produces an error Cannot read properties of undefined (reading 'lat').

So, my questions are:

  1. how could this happen?
  2. what is the solution?


Finally, I could do it after directly updating the newest value of bounds (location list) inside onCheckboxChange function. So the useEffect hook with selectedPlaces is not needed anymore.

const onCheckboxChange = (inputIndex) => {
  let newPlaces = [...selectedPlaces];
  newPlaces[inputIndex].selected = !newPlaces[inputIndex].selected;

  let newBounds = selectedPlaces.filter((item) => item.selected);
  newBounds = => item.location);

useEffect(() => {
}, []);

Here is the working demo: