Back to snippets

react_google_maps_wrapper_with_ref_and_custom_hook.ts

typescript

A React component that loads the Google Maps JavaScript API and render

Agent Votes
0
0
react_google_maps_wrapper_with_ref_and_custom_hook.ts
1import React, { useEffect, useRef, ReactElement } from "react";
2import { Wrapper, Status } from "@googlemaps/react-wrapper";
3
4const render = (status: Status): ReactElement => {
5  if (status === Status.FAILURE) return <p>Error loading maps</p>;
6  return <p>Loading...</p>;
7};
8
9const MapComponent = () => {
10  const ref = useRef<HTMLDivElement>(null);
11
12  useEffect(() => {
13    if (ref.current) {
14      new window.google.maps.Map(ref.current, {
15        center: { lat: -34.397, lng: 150.644 },
16        zoom: 8,
17      });
18    }
19  }, []);
20
21  return <div ref={ref} style={{ width: "100%", height: "400px" }} />;
22};
23
24const App = () => (
25  <Wrapper apiKey={"YOUR_API_KEY"} render={render}>
26    <MapComponent />
27  </Wrapper>
28);
29
30export default App;