1

I need something to run in a script tag, and I am using dangerouslySetInnetHTML to do so. It seems to be working just fine on another app, but nothing is being called in this case. I'm not sure if I am doing this the wrong way or there is something else. This is what my code in the component's render function looks like:

render () {
  return (
    <div>
        <div>
          Other component things
        </div>
        <script type='text/javascript' dangerouslySetInnerHTML={{
          __html: `console.warn('HELLOOOOO'); doSomething()`
        }}></script>
      </div>
  )
}
theJuls
  • 6,788
  • 14
  • 73
  • 160
  • 1
    This is going to be added through `innerHTML` which means it won't be executed. See [Can scripts be inserted with innerHTML?](https://stackoverflow.com/q/1197575/691711) – zero298 Feb 25 '19 at 17:03
  • 2
    Possible duplicate of [Can scripts be inserted with innerHTML?](https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml) – zero298 Feb 25 '19 at 17:04
  • did you try with a `div`? Same issue? – Subhendu Kundu Feb 25 '19 at 17:05
  • `I'm not sure if I am doing this the wrong way` I'd say so, it's not really the React way.. What is it exactly your wanting to do. You of course could just put that code at the start of your `render` and it's going to get executing on `render`, for other lifecycle time, there is things like `ComponentDidMount` etc, although I like using hooks so it would be `useEffect` etc. – Keith Feb 25 '19 at 17:09
  • @Keith, the issue is i am attempting to run a function from an external file, which is in my `static` folder, more specifically the [iFrameResizer](https://github.com/davidjbradshaw/iframe-resizer). What would be another way for me to get their script to be used the react way? – theJuls Feb 25 '19 at 17:12
  • 1
    Just include the scripts in your normal HTML, and not your mounted react controls. Or alternatively load the script dynamically using some script loader. – Keith Feb 25 '19 at 17:15
  • see if react-helmet can solve your issue and I think it should as it allows adding script tags in head and body – Dhaval Chheda Feb 25 '19 at 17:15
  • @Keith I am including the script in my `Head` file which for all intense and purposes I believe would be the same. The issue is calling. – theJuls Feb 25 '19 at 17:23
  • @SubhenduKundu Doing with a div is no help unfortunately. – theJuls Feb 25 '19 at 17:23
  • Possible duplicate of [React: Script tag not working when inserted using dangerouslySetInnerHTML](https://stackoverflow.com/questions/35614809/react-script-tag-not-working-when-inserted-using-dangerouslysetinnerhtml) – Michael Freidgeim Sep 05 '19 at 12:01

0 Answers0