-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
26 additions
and
2 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
packages/react-components/src/components/dangerous-element.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import React, { useRef, useLayoutEffect } from 'react' | ||
/** | ||
* Execute a script tag in a React component. | ||
* https://macarthur.me/posts/script-tags-in-react/ | ||
*/ | ||
function DangrousElement({ markup }: { markup: string }) { | ||
const elRef = useRef<HTMLDivElement>(null) | ||
|
||
useLayoutEffect(() => { | ||
if (!elRef.current) return | ||
const range = document.createRange() | ||
range.selectNode(elRef.current) | ||
const documentFragment = range.createContextualFragment(markup) | ||
|
||
// Inject the markup, triggering a re-run! | ||
elRef.current.innerHTML = '' | ||
elRef.current.append(documentFragment) | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []) | ||
|
||
return <div ref={elRef} dangerouslySetInnerHTML={{ __html: markup }}></div> | ||
} | ||
|
||
export default DangrousElement |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters