uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.61k stars 128 forks source link

Using React component in decorations #398

Open jodyheavener opened 1 year ago

jodyheavener commented 1 year ago

Is there a known solution for using a React component in a widget decoration?

I initially thought that I could perhaps use a Portal, where it queried the CodeMirror editor after render and then replaced an empty widget with my component, like:

const Code = () => {
  const cmRef = React.useRef<ReactCodeMirrorRef>({});

  return (
    <>
      <CodeMirror ref={cmRef} />

      <WidgetPortal {...{ cmRef }}>
        <Widget />
      </WidgetPortal>
    </>
  );
};

const WidgetPortal = ({
  children,
  cmRef,
}: {
  children: React.ReactNode;
  cmRef: React.MutableRefObject<ReactCodeMirrorRef>;
}) => {
  const targetEl = cmRef.current?.editor?.querySelector(".widget");
  return targetEl ? ReactDOM.createPortal(children, targetEl) : null;
};

But this doesn't seem to work - no errors are thrown and the empty widget container is still in the DOM so I assume the CodeMirror component is rendering in a way that is preventing my portal from mounting.

Is there any other way you think this could be achieved?

jaywcjlove commented 1 year ago

https://github.com/uiwjs/react-codemirror/blob/b2341d3f8fb94345cbb759382870d81c61606812/extensions/color/src/index.ts#L60-L70

@jodyheavener I'm sure it should be difficult to use Portal to implement widget decoration.