sjdemartini / mui-tiptap

A Material UI (MUI) styled WYSIWYG rich text editor, using Tiptap
MIT License
319 stars 43 forks source link

`ref` failure in Nextjs project #207

Closed kblizeck closed 7 months ago

kblizeck commented 7 months ago

Describe the bug

I am importing mui-tiptap dynamically into a Nextjs component. I am receiving a Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? error.

To Reproduce

Please include a CodeSandbox demo of the problem if possible. Code Sandbox

Steps to reproduce the behavior:

  1. Install and dynamically load mui-tiptap in Nextjs project (app router)
  2. Try to preset content in the editor
  3. Console error about ref preventing content load.

Expected behavior

Ref should be used in RichTextEditor as expected

Screenshots

If applicable, add screenshots to help explain your problem.

System (please complete the following information)

      BulletList,
      Document,
      ListItem,
      OrderedList,
      Paragraph,
      Text,
      Bold,
      Italic,
      Underline,
      HeadingWithAnchor,
      History,
sjdemartini commented 7 months ago

Thanks for including the CodeSandbox. I'm honestly not familiar enough with NextJS to debug this or understand the issue.

I see you're using:

const RichTextEditor = useMemo(
    () =>
      dynamic(
        import("mui-tiptap").then((module) => module.RichTextEditor),
        {
          ssr: false,
        },
      ),
    [],
  );

Their docs on lazy imports do seem to show a different pattern for external libraries than for internal code: https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-external-libraries (await import() rather than dynamic(...)).

The docs on dynamic() also do say:

dynamic() can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to React.lazy.

So it seems to me that perhaps the import pattern you're using may not be valid. 🤔

kblizeck commented 7 months ago

@sjdemartini I tried moving the import but that didn't solve the issue - instead, I had to add another wrapper component that uses forwardRef to pass the ref to the RichTextEditor component. I updated the example here - https://codesandbox.io/p/devbox/mui-tiptap-editor-npxsf8?file=%2Fapp%2Fdocument.js

Thank you for taking a look! Going to close this issue out.