Ad

Access Callback In React

- 1 answer

Google API JS library returns a callback on successful load.

<script src="https://apis.google.com/js/client.js?onload=callback"></script>

Can someone explain how to integrate this callback into React application with server-side rendering? In vanilla js it will something like this:

function callback() {
  gapi.auth.authorize({...});
}
Ad

Answer

It depends on exactly what you're doing. Let's assume you want to enact a state change on that callback. You could put the following in your React component:

componentWillMount() {
    if (typeof window === 'undefined') {
        return; // client side only
    }
    window.callback = () => {
        this.setState({
            isAuthorized: true
        });
    };
}

Just make sure this callback is defined before you call the remote resource. i.e. Put your React scripts before the Google script.

Ad
source: stackoverflow.com
Ad