0

New to coding and react in general. I am wondering how to get this script(widget) from me index.html to appear in a component

index.html

// <div id="cibtWidgetHolder"></div>

    <script type="text/javascript">
      var gaJsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
      var widgetHost = (("https:" == document.location.protocol) ? "https://" : "http://");
      document.write(unescape("%3Cscript src='" + gaJsHost + "stats.g.doubleclick.net/dc.js' 
      type='text/javascript'%3E%3C/script%3E"));
      document.write(unescape("%3Cscript src='"+ widgetHost + "cibtvisas.com/widget/widgetv2.js? 
method=js&cibtCitizenship=USA&cibtCode=65490&cibtURL=balboa.com&cibtBG=e1f0f2&cibtHeader=1c171c&lang=en&cibtWidgetVersion=3' type='text/javascript'%3E%3C/script%3E"));
      </script>

sections.js

  <Col md="3">
  <div id="cibtWidgetHolder"></div>
  </Col>

If I call the div in index.html, it renders, but only at the bottom of the page, not with my other content in sections.js

I've seen this sort of usage for others asking similar questions, but am not sure how to implement with mine:

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};
export default useScript;

Any help is appreciated!

3
  • 1
    This is not something that should be within a rendered section. Commented Dec 3, 2019 at 20:58
  • can you clarify? If creating it in it's own component will work, then calling that component in section.js would work, I would do that, but I still fall back to not knowing what my next step is. Thank you Commented Dec 3, 2019 at 21:01
  • You may be able to improve from this SO stackoverflow.com/questions/46035999/… Commented Dec 3, 2019 at 21:45

1 Answer 1

-1

If you are determined to add a script element to a react app then it may be worth checking out react-helmet or react-helmet-async.

This library will let you add script elements and other meta tags to the html in probably the cleanest way.

That being said there is probably a more efficient way using useEffect or onComponentMount for this process.

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

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.