Last active
April 29, 2024 09:36
-
-
Save aiphee/fd5393ae7614ff3d34bfb33c00bb68df to your computer and use it in GitHub Desktop.
Fragment with dangerouslySetInnerHtml replacement -
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
import React from 'react'; | |
interface IProps { | |
children: unknown; | |
} | |
/** | |
* Takes node content and makes JSX element out of it (kind of like dangerouslySetInnerHTML) | |
* Careful, always sanitize input! | |
* credit @yairEO https://github.com/facebook/react/issues/12014#issuecomment-1621382570 | |
* | |
* Usage: `React.createElement(StringToNode, null, stringContent)` | <StringToNode>{stringContent}</StringToNode> | |
*/ | |
const StringToNode = React.memo(({ children }: IProps) => { | |
const ref = React.useRef(); | |
React.useEffect(() => { | |
if (ref.current) { | |
(ref.current as HTMLSpanElement).outerHTML = children as string; | |
} | |
}, [children]); | |
return <span ref={ref} />; | |
}); | |
export default StringToNode; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment