Skip to content

Instantly share code, notes, and snippets.

@aiphee
Last active April 29, 2024 09:36
Show Gist options
  • Save aiphee/fd5393ae7614ff3d34bfb33c00bb68df to your computer and use it in GitHub Desktop.
Save aiphee/fd5393ae7614ff3d34bfb33c00bb68df to your computer and use it in GitHub Desktop.
Fragment with dangerouslySetInnerHtml replacement -
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