Run a Script in React JS/TSX file

Viewed 905

I have a ReactJs file, Component.js and I want to execute a Script which looks like this:

<script type='text/javascript'>
    window.onAmazonLoginReady = function() {
      amazon.Login.setClientId('CLIENT-ID');
    };
    window.onAmazonPaymentsReady = function() {
      //Will also add this button implementation method
      showButton();
    };
  </script>

I want to include this Script in Component.js file, but couldn't think of any way. I had included this in index.js/index.html but I want the above script to be executed when the Component.js file loads. This is my component.js file:

import React, { useContext, Component } from 'react';
import { Link } from 'react-router-dom';
const Component = () => {
    return (
        <div> Hello from Component </div>
    );
};
export default Component;
1 Answers

You can just add the script inside the useEffect of the Component.js file like this :

useEffect(() => {  
    const setLoginClientId = () => {
      amazon.Login.setClientId('CLIENT-ID');
    };
    // If this "onAmazonLoginReady" is a javascript event then you should add like this
    // window.addEventListener("onAmazonLoginReady",setLoginClientId);
    window.onAmazonLoginReady = setLoginClientId;

    // Removed the unncessary function inside function, 
    // you can directly call showButton now
    window.onAmazonPaymentsReady = showButton;

    //Calling Set Client Id once, if you want 
    setLoginClientId();

 },[]);

This will only run one time just after the Component loads.

Related