I want to load the Google APIs client library inside my index.html
and the onLoad='someMethod'
will invoke a method in a separate javascript file. That method will then print out to the console.
The client library is loaded without any problems but the message is not getting printed out the console and I think it's because the method is not getting invoked at all.
Here is my index.html
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div id="app"></div> <script src="lib/vendors.js"></script> <script src="build/bundle.js"></script> <script src="https://apis.google.com/js/client.js?onload=handleGoogleClientLoad"></script> </body>
Here is the javascript file that contains the handleGoogleClientLoad
method:
import React from 'react'; import ReactDOM from 'react-dom'; import {Button} from 'react-bootstrap'; class MyApp extends React.Component { handleGoogleClientLoad() { console.log('Success on load'); } render() { return ( <div> <Button>Click Me</Button> </div> ); } } const app = document.getElementById('app'); ReactDOM.render(<MyApp />, app);
If this was plain javascript the method would look like this:
window.handleGoogleClientLoad = function() { // Log to the console };
Is there anything in es6 that is similar to the window
object.
Any property attached to the window object can be accessed from any script on the web page, including the script for the React app. Since window is a global object, the React code can also access its properties, as shown below.
To use the addEventListener method in function components in React: Set the ref prop on the element. Use the current property on the ref to get access to the element. Add the event listener in the useEffect hook.
Component methods are not attached to the window
object. MyApp.handleGoogleClientLoad
is not going to be aliased to window.handleGoogleClientLoad
which is what the google API script is likely trying to invoke.
If you want the Google API to call a method on your component you're going to have some trouble as there's no guarantee that your component will be mounted before or after your Google API script loads. If you want to guarantee that you'd have to inject the script after the component mounted and register the function in the componentDidMount
method. You can use something like loadjs
componentDidMount() { window.handleGoogleClientLoad = function() { // log to console } loadjs('https://apis.google.com/js/client.js?onload=handleGoogleClientLoad') }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With