fullstackreact / google-maps-react

Companion code to the "How to Write a Google Maps React Component" Tutorial
https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/
MIT License
1.63k stars 815 forks source link

Fixing the map position and width #494

Open 1nfinity-5starZ opened 3 years ago

1nfinity-5starZ commented 3 years ago

The way styles are applied are way off, so I came up with a little hack to decouple the ApiWrapper from the UI, here goes the code:

import React, { useEffect, useState } from "react";
import { GoogleApiWrapper, Map } from "google-maps-react";

function ParentComponent(props) {
  const [google, setGoogle] = useState();
  return (
    <div style={{ position: "relative", width: "100%", maxHeight: 500 }}>
      <GoogleProvider onChange={(google) => setGoogle(google)} />
      <Map google={google} />
    </div>
  );
}

function Wrapper(props) {
  useEffect(() => {
    props.onChange(props.google);
  }, [props.google]);

  return null;
}

const GoogleProvider = GoogleApiWrapper({
  apiKey: "",
})(Wrapper);

export default ParentComponent;

The trick is to create a separate component and then pass the google prop up in the hierarchy and store it in the state. Works with flexbox.

Shahaed commented 3 years ago

Worked like a charm. Thanks, @1nfinity-5starZ