Onerror and onload events dont fire in script element in react

Viewed 437

i am trying to fetch a script from stripe dynamically inside my react component. Getting the script the

|script src="https://js.stripe.com/v3/">

type of way worked. However in react it seems that the onerror and onload events just don't fire.

https://codesandbox.io/s/nn4kk55rr0

or:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  showLoad = () => {
    console.log("loaded");
  };
  showError = () => {
    console.log("error");
  };
  fetchStripe = () => {
    console.log("fetching");
    var stripe = document.createElement("script");
    stripe.onload = this.showLoad;
    stripe.onerror = this.showError;
    stripe.src = "https://js.stripe.com/v3/";
  };
  componentDidMount() {
    this.fetchStripe();
  }
  render() {
    return <div className="App">Hallo</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Thanks for any help in advance!

1 Answers

You need to append it to <head> to start the loading, otherise it is still in memory not present in the DOM so browser will not parse it. So add this also after the line stripe.src = "https://js.stripe.com/v3/"; :

document.getElementsByTagName('head')[0].appendChild(stripe);
Related