ぶちのブログ

競プロとCTFが趣味なWebエンジニアのアウトプットの場

google-picker-apiをReact hooks + TypeScriptで使う実装例

はじめに

使うかなと思って実装したら全く使わなかったので供養。

実装例

import * as React from 'react';

interface Props {
  onChange: (data: any) => void;
}

export default function Picker(props: Props): JSX.Element {
  const { onChange } = props;
  React.useEffect(() => {
    const onScriptLoad = (): void => {
      window.gapi.load('picker', () => {
        new window.google.picker.PickerBuilder()
          .addView(
            new window.google.picker.MapsView()
              .setCenter(35.681236, 139.767125)
              .setZoom(14)
          )
          .setLocale('ja')
          .setCallback(onChange)
          .setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
          .build()
          .setVisible(true);
        var elements= document.getElementsByClassName('picker-dialog');
          for(var i=0;i<elements.length;i++){
            (elements[i] as any).style.zIndex = "100000";
          }
      });
    };

    if (!window.gapi) {
      const s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = `https://apis.google.com/js/api.js`;
      const x = document.getElementsByTagName('script')[0];
      if (x.parentNode !== null) {
        x.parentNode.insertBefore(s, x);
        s.addEventListener('load', () => {
          onScriptLoad();
        });
      }
    } else {
      onScriptLoad();
    }
  }, [onChange]);
  return <></>;
}