I'm making a map with react and react-leaflet. React Leaflet has a class called FeatureGroup, which I want to access on the first render using the useRef hook from React and then accessing the value in a useEffect function. However on initial render the ref is undefined (markerRef.current returns null). Only after I make any sort of changes to the code, save and the React app reloads it gets the value
Can you tell me what I'm doing wrong and how I can make it so that markerRef.current is not null on the initial render?
Please find the abbreviated code for the component below:
import {useRef} from 'react';
import {FeatureGroup, //... } from 'react-leaflet';
const MapView = ({breweries}) => {
const markerGroupRef = useRef(null);
//...
useEffect(() => {
if(markerGroupRef.current) {
//here I want to access a method called getBounds() which is in the markerGroupRef.current object
//but markerGroupRef.current has null value and so it doesn't execute
//when making a save change and react app reloads it has the FeatureGroup class as value as expected
console.log(markerGroupRef.current)
}
}, [markerGroupRef])
//...
return (
<FeatureGroup ref={markerGroupRef}>
{breweries && breweries.map(brewery => <Brewery key={breweries.indexOf(brewery)} brewery={brewery}/>)}
{breweryStore && breweryStore.searchLocation && <LocationMarker markerPosition={{lat: breweryStore.searchLocation.lat, lng: breweryStore.searchLocation.lon}}/>}
</FeatureGroup>
);
}