Adding script tag to React/JSX

后端 未结 17 1192
感动是毒
感动是毒 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:18

    A bit late to the party but I decided to create my own one after looking at @Alex Macmillan answers and that was by passing two extra parameters; the position in which to place the scripts such as or and setting up the async to true/false, here it is:

    import { useEffect } from 'react';
    
    const useScript = (url, position, async) => {
      useEffect(() => {
        const placement = document.querySelector(position);
        const script = document.createElement('script');
    
        script.src = url;
        script.async = typeof async === 'undefined' ? true : async;
    
        placement.appendChild(script);
    
        return () => {
          placement.removeChild(script);
        };
      }, [url]);
    };
    
    export default useScript;
    

    The way to call it is exactly the same as shown in the accepted answer of this post but with two extra(again) parameters:

    // First string is your URL
    // Second string can be head or body
    // Third parameter is true or false.
    useScript("string", "string", bool);
    

提交回复
热议问题