Search code examples
reactjsjsxdangerouslysetinnerhtml

Using createContextualFragment with JSX


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>
    );
}

Solution

  • For any direct interaction with the DOM, you need a React ref. What you want can be implemented with useRef and useEffect:

    const ContextualComponent = ({ html }) => {
      const ref = useRef(null);
    
      useEffect(() => {
        const { current } = ref;
    
        const documentFragment = document
          .createRange()
          .createContextualFragment(html);
    
        current.appendChild(documentFragment);
    
        return () => {
          current.textContent = "";
        };
      }, [html]);
    
      return <div ref={ref} />;
    };
    

    CodeSandbox demo