Adding script tag to React/JSX

后端 未结 17 931
感动是毒
感动是毒 2020-11-22 03:52

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

\'use strict\';

import \'../../styles/         


        
相关标签:
17条回答
  • 2020-11-22 04:31

    My favorite way is to use React Helmet – it's a component that allows for easy manipulation of the document head in a way you're probably already used to.

    e.g.

    import React from "react";
    import {Helmet} from "react-helmet";
    
    class Application extends React.Component {
      render () {
        return (
            <div className="application">
                <Helmet>
                    <script src="https://use.typekit.net/foobar.js"></script>
                    <script>try{Typekit.load({ async: true });}catch(e){}</script>
                </Helmet>
                ...
            </div>
        );
      }
    };
    

    https://github.com/nfl/react-helmet

    0 讨论(0)
  • 2020-11-22 04:36

    You can use npm postscribe to load script in react component

    postscribe('#mydiv', '<script src="https://use.typekit.net/foobar.js"></script>')
    
    0 讨论(0)
  • 2020-11-22 04:40

    Further to the answers above you can do this:

    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)} />;
      }
    }
    

    The div is bound to this and the script is injected into it.

    Demo can be found on codesandbox.io

    0 讨论(0)
  • 2020-11-22 04:40

    If you need to have <script> block in SSR (server-side rendering), an approach with componentDidMount will not work.

    You can use react-safe library instead. The code in React will be:

    import Safe from "react-safe"
    
    // in render 
    <Safe.script src="https://use.typekit.net/foobar.js"></Safe.script>
    <Safe.script>{
      `try{Typekit.load({ async: true });}catch(e){}`
    }
    </Safe.script>
    
    0 讨论(0)
  • 2020-11-22 04:41

    for multiple scripts, use this

    var loadScript = function(src) {
      var tag = document.createElement('script');
      tag.async = false;
      tag.src = src;
      document.getElementsByTagName('body').appendChild(tag);
    }
    loadScript('//cdnjs.com/some/library.js')
    loadScript('//cdnjs.com/some/other/library.js')
    
    0 讨论(0)
提交回复
热议问题