简体   繁体   中英

How can I load a script for just one component?

I have this generated code for insert Privacy Policy to Website, but if I set this script in index.html I have this block on all pages, but I need only one page (one component).

<div id="__enzuzo-root"></div>
<script id="__enzuzo-root-script" src="..."></script>

Also, I have issue with inserting block to <div id="__enzuzo-root"... I added useEffect for inserting script tag after render but it does not work

import React, { useEffect } from 'react';

const TermsOfService = _ => {
    useEffect(() => {
        const script = document.createElement("script");
        script.src = "https://app.enzuzo.com/__en...";
        script.async = true;
        document.body.appendChild(script);
    }, [])

    return (
        <React.Fragment>
            <div id="__enzuzo-root"></div>
        </React.Fragment>
    );
}

export default TermsOfService;

Do you have any idea?

Firstly try useLayoutEffect which runs after the DOM has actually been rendered.

Secondly your div ID doesn't match the snippet.

You might also detect when script it loaded and trigger a page load event as the lib might be listening to it.

const TermsOfService = _ => {
    useLayoutEffect(() => {
        const script = document.createElement("script");
        script.src = "https://app.enzuzo.com/__en...";
        script.async = true;
        script.onload = () => {
           dispatchEvent(new Event('load'))
           dispatchEvent(new Event('DOMContentLoaded'))
        }
        document.body.appendChild(script);
    }, [])

    return (
        <React.Fragment>
            <div id="__enzuzo-root"></div>
        </React.Fragment>
    );
}

export default TermsOfService;

I used iframe and everything worked

<iframe srcDoc={`<div id="__enzuzo-root-tos"></div><script src="..." type="text/javascript"></script>`} />

In order to add any script to the react component you have to use some packages like React Helmet.Please visit here and follow the instructions: https://www.npmjs.com/package/react-helmet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM