Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access callback in React

Tags:

reactjs

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({...});
}
like image 784
Kertis van Kertis Avatar asked Dec 03 '25 15:12

Kertis van Kertis


1 Answers

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.

like image 168
David L. Walsh Avatar answered Dec 06 '25 07:12

David L. Walsh