'Map In Child Component Does Not Re-render On State Change
I am building a React app with Capacitor and the Google Maps Plugin.
I have a page that loads two components that are conditionally rendered.
The Partent Component:
const [viewType, setViewType] = useState('map');
{ viewType === 'map' && <RenderMaps viewType={viewType}></RenderMaps>}
{ viewType === 'list' && <ViewCardList></ViewCardList>}
The state is changed here:
<ViewSelectorBar id={"viewSelectorBar"} viewType={viewType} setViewType={setViewType} ></ViewSelectorBar>
My state seems to be changing fine (I can switch between the two views fine), but the map does not rerender. And actually, when I go to my dev tools to inspect in the React Components plugin, I search for my component name RenderMaps, and the map rerenders.
Here is the RenderMaps.tsx:
interface Props {
viewType: string;
}
const RenderMaps = ({viewType}: Props) => {
const mapRef = useRef<HTMLElement>();
const key: string = process.env.REACT_APP_GOOGLE_MAPS_API ?? "broken-key";
let newMap: GoogleMap;
const [mapConfig, setMapConfig] = useState({
zoom: 10,
center: {
lat: 46.3527,
lng: -94.2020
},
disableDefaultUI: true
})
const createMap = async () => {
if (!mapRef.current) return;
newMap = await GoogleMap.create({
id: 'google-map',
element: mapRef.current,
apiKey: key,
config: mapConfig
});
}
if (viewType === 'map') {
createMap();
}
return (
<capacitor-google-map id="mapContainer" ref={mapRef}>
</capacitor-google-map>
)
}
export default RenderMaps;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
