Home > Net >  How can I load a script for just one component?
How can I load a script for just one component?

Time:10-01

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?

CodePudding user response:

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;

CodePudding user response:

I used iframe and everything worked

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

CodePudding user response:

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

  • Related