const [markers, setMarkers] = React.useState([]);
const mapRef = React.useRef();
React.useEffect( () => {
fitBounds();
}, [markers])
const fitBounds = () => {
const bounds = new window.google.maps.LatLngBounds();
markers.map(place => {
bounds.extend(place);
});
mapRef.current.fitBounds(bounds);
};
In the above code snippet im trying to resize the map to the fit the window in which all markers can be seen. I want this to occur everytime a new marker is added so I though a good place to put it would be in the useEffect() function. However I keep getting the Error: TypeError: Cannot read property ‘fitBounds’ of undefined. Im fairly new to react so if someone could explain to me how I can achieve this functionality Id really appreciate it.
I think the error is coming from this line within your
fitBounds()
function:It’s likely trying to call it before the ref has finished setting.
Try bailing out of the function early if it’s not ready, e.g.: