A script tag inside dangerouslySetInnerHTML never executes
The script tag is visible in DevTools Elements but its code never runsShort answer
Browsers do not run script elements that are injected through innerHTML, and dangerouslySetInnerHTML sets innerHTML. The script shows up in the DOM but never executes. Render a script component with src instead, or create the script element in a useEffect and remove it in cleanup. Do not try to sanitize your way into running it.
Fix it fast
1Find out which cause you have
Open DevTools, find the script element in the Elements panel, and check whether the global it should define exists.
console.log(typeof window.widget)2Match what you see, then jump to its fix
- 1
The script element is in the DOM, no network request for its src, nothing runsinnerHTML never executes injected script elementsFix - 2
The script request succeeds, but the first call to its global failsYour code runs before the script has loadedFix - 3
You use an older React, or need exact control over when the tag is added and removedYou must add the script from an effect, with cleanupFix
- 1
What does the error look like?
The script tag is visible in DevTools Elements but its code never runsReferenceError: widget is not defined, when code expects the injected script to have loaded
Cause 1 of 3
innerHTML never executes injected script elements
1Check
dangerouslySetInnerHTML overrides the node's innerHTML. MDN says innerHTML prevents script elements from executing when they are injected.
grep -rn "dangerouslySetInnerHTML" src/2Fix
Stop passing the script as HTML. Render a script component with src and async. React 19 can hoist it to the head and de-duplicate scripts with the same src.
function Widget() {
return (
<>
<script async src="https://example.com/widget.js" />
<div id="widget-root" />
</>
)
}3Verify
The network panel shows the request and the global exists.
console.log(typeof window.widget)Confirmed by react.dev
Cause 2 of 3
Your code runs before the script has loaded
1Check
React docs warn that a component can be committed before its script finishes loading. Use the load event before calling into it.
grep -rn "widget\." src/2Fix
Start your code from the onLoad prop. Note that adding onLoad or onError disables React's de-duplication and head hoisting for that script.
<script async src="https://example.com/widget.js"
onLoad={() => window.widget.init('#widget-root')} />3Verify
Reload the page and watch the console stay clean.
console.log(typeof window.widget.init)Confirmed by react.dev
Cause 3 of 3
You must add the script from an effect, with cleanup
1Check
An effect is the place to connect to something React does not control. Its cleanup must undo the setup.
grep -rn "useEffect" src/Widget.jsx2Fix
Create the script element with document.createElement, append it in the effect and remove it in the returned cleanup.
useEffect(() => {
const s = document.createElement('script')
s.src = 'https://example.com/widget.js'
s.async = true
document.body.appendChild(s)
return () => { document.body.removeChild(s) }
}, [])3Verify
Mount and unmount the component; the tag appears and disappears.
document.querySelectorAll('script[src*="widget"]').lengthConfirmed by react.dev
How do I stop it coming back?
- Never put third-party snippets into dangerouslySetInnerHTML; React says to use it only with trusted and sanitized data.
- Load third-party scripts with src, async and an onLoad handler.
- Check what a snippet defines globally before calling it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix