Home > Software engineering >  Script dynamically inserted later on: how to make it run?
Script dynamically inserted later on: how to make it run?

Time:04-15

In my React app, I have scripts that are inserted dynamically later on. The scripts don't load.

A field called content in my database for example contains data such as the following:

<p>Some text and html</p>
<div id="xxx_hype_container" style="width: 46px; height: 50px; overflow: hidden;">
<script type="text/javascript" charset="utf-8" src="https://example.com/uploads/hype_generated_script.js?499892"></script>
</div>
<div style="display: none;" aria-hidden="true"> 
<div>Some text.</div> 
Etc…

In my React app, I call on this db field to display that content:

import { thePost } from "../../../appRedux/actions/postAction";

class Post extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            post: "",
        };
    }

    componentDidMount() {
        // get post data from db
        this.props.thePost(this.props.match.params.postId);
    }

    render() {
        return (
            <div className="container">
                {post.content}
            </div>
        )
    }
}

It correctly loads the data from the database and displays the html from that data. But the data also contains a script, which does NOT get loaded. I think the script doesn't work because it is dynamically inserted later on. How can I make this script work/run?

This post suggest a solution for dynamically inserted scripts, but I don't think I can apply this solution because in my case the script/code is loaded from a database (so how to then use nodeScriptReplace on the code...?). Any suggestions how I might make my scripts work?


Update:

With the code below, it still did not run the script.

    render() {
        return (
            <div className="container">
                <div dangerouslySetInnerHTML={{ __html: post.content }} />
            </div>
        )
    }

CodePudding user response:

Rendering raw HTML without React recommended method is not a good practice. React recommends method dangerouslySetInnerHTML to render raw HTML.

CodePudding user response:

There are various ways to do this. You may create a function that can be called on to dynamically create and inject the <script> tag into the <body> of the React application.

const addScript = () => {
    const script = document.createElement("script");
    script.src = '<url-of-the-script>';
    script.async = true;
    script.onload = function() {
        // Do something
    };
    document.head.appendChild(script);
}

You may call this addScript function when the required component loads using the useEffect hook.

useEffect(() => {
    addScript();
    return () => {
        // remove the script on component unmount
    };
}, []);
  • Related