2

I have a script like:

 <div id="widget"></div>
          <script
            type="text/javascript"
            src="https://widget.io/w.js"
          ></script>
          <script type="text/javascript">
              new Widget({
                width: 768,
                height: 525,
                containerId: "widget",
                partner_id: "default",
           
              })
          </script>

That I need to trigger within a react component.

I've seen the other questions related to this and its working using their examples - except for the new Widget({}) params.

React is saying Widget is not defined, as its not imported from anywhere.

I'm using react helmet for adding the script tag, so my render() function looks like this:


  render() {
    return (
      <div id="wert-widget">
        <Helmet>
 <div id="widget"></div>
          <script
            type="text/javascript"
            src="https://widget.io/w.js"
          ></script>
          <script type="text/javascript">
             {
                new Widget({
                width: 768,
                height: 525,
                containerId: "widget",
                partner_id: "default",
           
              })
              }
          </script>
        </Helmet>
      </div>
    );
  }

But react throws an error saying Widget is not defined.

Using the setInnerHTML in a componentDidMount function, also does not work, as it just sets the new Widget object as a string and doesn't initialize the widget.

How would you do this in react?

Adding it into the HTML index.html directly isn't helpful as we only need this widget on one component when a user clicks a button.

1 Answer 1

2
componentDidMount() {
  const script = document.createElement("script");
  script.src = "/static/libs/your_script.js";
  script.async = true;
  script.onload = () => this.scriptLoaded();

  element.appendChild(script);
}
Sign up to request clarification or add additional context in comments.

1 Comment

How do you add the class info to the script - ` new Widget({})`?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.