I am trying to include a "contextual component" in JSX, what am I doing wrong?
Note that I need the scripts to run, so dangerouslySetInnerHTML is not an option. Also I'd like to build a Function Component for use with hooks.
export default function ContextualComponent() {
const node = document.createRange().createContextualFragment("<div>My html and scripts</div>");
return (
<div>{node}</div>
);
}
For any direct interaction with the DOM, you need a React ref. What you want can be implemented with
useRef
anduseEffect
:CodeSandbox demo