Using createContextualFragment with JSX

874 views Asked by At

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

There are 1 answers

1
Lionel Rowe On BEST ANSWER

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