HI WELCOME TO KANSIRIS

Adding script tag to React/JSX or How to add script tag using ReactJS?

Leave a Comment
Do you want to fetch and execute the script again and again, every time this component is rendered, or just once when this component is mounted into the DOM?
Perhaps try something like this:
    componentDidMount () {
        const script = document.createElement("script");

        script.src = "https://use.typekit.net/foobar.js";
        script.async = true;

        document.body.appendChild(script);
    }
However, this is only really helpful if the script you want to load isn't available as a module/package. First, I would always:
  • Look for the package on npm
  • Download and install the package in my project (npm install typekit)
  • import the package where I need it (import Typekit from 'typekit';)
This is likely how you installed the packages react and react-document-title from your example, and there is a Typekit package available on npm.


 import React from 'react';

export default class Test extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.innerHTML = "document.write('This is output by document.write()!')";
    this.instance.appendChild(s);
  }

  render() {
    return <div ref={el => (this.instance = el)} />;
  }
}



0 comments:

Post a Comment

Note: only a member of this blog may post a comment.