gapi is not defined when loading React Component

It looks to me like you're loading the google apis as a script tag, which we'd expect to set window.gapi to the google api. However, you're then running eslint or some other checker, and that has no idea that window.gapi is supposed to exist. It's failing because it sees you using an undeclared variable.

A cheap fix is to tell Eslint that you know what you are doing;

/* global gapi */

Put this at the top of your file and eslint will treat gapi as a known global variable.


This worked for me. Put it in componentDidMount or constructor:

componentDidMount() {
    window.gapi.load('auth2', () => {
        // Retrieve the singleton for the GoogleAuth library and set up the client.
        this.auth2 = window.gapi.auth2.init({
            client_id: '436676563344-.apps.googleusercontent.com',
            cookiepolicy: 'single_host_origin',
        });

        this.auth2.attachClickHandler(this.refs.googleButton, {},
            (googleUser) => {
                this.googleLogin(googleUser.getBasicProfile());
            }, (error) => {

            });
    });
}

You can also try the package gapi-script, this package provides the gapi instantly, so you don't have to wait any script to load, just import it and use:

import { gapi } from 'gapi-script';