Warning: ReactDOM: Expected `dangerouslySetInnerHTML` to be a string, but got `object` instead.
ID: react/warning-react-dom-production-minification-issue
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 16.14.0 | active | — | — | — |
Root Cause
The `dangerouslySetInnerHTML` prop expects an object with a `__html` key containing a string, but a raw object or non-string value was passed, often due to misusing the prop or passing a component/JSX element instead of HTML string.
generic中文
`dangerouslySetInnerHTML` 属性期望一个包含 `__html` 键的对象,其值为字符串,但传递了原始对象或非字符串值,通常是由于误用该属性或传递了组件/JSX 元素而不是 HTML 字符串。
Official Documentation
https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-htmlWorkarounds
-
95% success Correct the usage: pass an object with __html key containing a sanitized HTML string. Example: <div dangerouslySetInnerHTML={{ __html: '<p>Hello</p>' }} />
Correct the usage: pass an object with __html key containing a sanitized HTML string. Example: <div dangerouslySetInnerHTML={{ __html: '<p>Hello</p>' }} /> -
80% success If you're trying to render React components dynamically, use a different approach like using a state variable or a render prop instead of dangerouslySetInnerHTML.
If you're trying to render React components dynamically, use a different approach like using a state variable or a render prop instead of dangerouslySetInnerHTML.
-
90% success Sanitize the HTML string using a library like DOMPurify before passing it to dangerouslySetInnerHTML to prevent XSS attacks.
Sanitize the HTML string using a library like DOMPurify before passing it to dangerouslySetInnerHTML to prevent XSS attacks.
中文步骤
Correct the usage: pass an object with __html key containing a sanitized HTML string. Example: <div dangerouslySetInnerHTML={{ __html: '<p>Hello</p>' }} />If you're trying to render React components dynamically, use a different approach like using a state variable or a render prop instead of dangerouslySetInnerHTML.
Sanitize the HTML string using a library like DOMPurify before passing it to dangerouslySetInnerHTML to prevent XSS attacks.
Dead Ends
Common approaches that don't work:
-
Pass a plain string directly to dangerouslySetInnerHTML without the __html wrapper
95% fail
dangerouslySetInnerHTML requires an object with __html key; passing a string directly will cause a different error.
-
Use innerHTML property directly on the DOM element via ref
85% fail
Direct DOM manipulation bypasses React's reconciliation and can lead to inconsistencies, but it's also not the intended fix for this warning.
-
Ignore the warning because the HTML still renders
90% fail
The warning indicates a potential XSS vulnerability or incorrect rendering; ignoring it can lead to security issues or broken UI.