BlockNote icon indicating copy to clipboard operation
BlockNote copied to clipboard

Passing a new theme object causes editor to lose focus

Open jcubed111 opened this issue 1 year ago • 2 comments

Describe the bug I have a setup where:

  1. I set some state using BlockNoteView.onChange
  2. I dynamically set the theme object based on a context
const themeOptions = useContext(...);
const [doc, setDoc] = useState(...);

return <BlockNoteView
    theme={{...themeOptions, override: etc}}
    onChange={() => setDoc(...)}
>;

This causes the BlockNoteView to completely rerender whenever you type anything in it, and it loses focus in the process. The result is that you type one character, then have to refocus before you can type more.

What appears to be happening is that the editor thinks the theme has changed (which, I suppose, it could have) and rebuilds from scratch.

I can work around this by wrapping the theme object in a useMemo, but reporting since I only started seeing this error after upgrading from 0.11.2 to 0.12.1.

To Reproduce https://stackblitz.com/edit/github-v9k2jl?file=App.tsx

import '@blocknote/core/fonts/inter.css';
import {
  BlockNoteView,
  lightDefaultTheme,
  useCreateBlockNote,
} from '@blocknote/react';
import '@blocknote/react/style.css';
import { useState } from 'react';

export default function App() {
  const [obj, setObj] = useState({});

  const editor = useCreateBlockNote({
    initialContent: [
      {
        type: 'paragraph',
        content: 'Try typing',
      },
    ],
  });

  return (
    <BlockNoteView
      editor={editor}
      onChange={() => setObj({})}
      theme={{ ...lightDefaultTheme }}
    />
  );
}

Misc

  • Node version: 20.9.0
  • Package manager: npm
  • Browser: Chrome & Firefox both have this issue

jcubed111 avatar Mar 26 '24 09:03 jcubed111

The reason is probably because the internal refs (containerRef and mount) are mixed here: https://github.com/TypeCellOS/BlockNote/blob/a5cf36af43fb5ffa50381e9bfa389008bca17d4a/packages/react/src/editor/BlockNoteView.tsx#L195

It's fixable, but for now I think useMemo is an ok solution

YousefED avatar Mar 27 '24 09:03 YousefED

Can I try to fix this problem?

jijiseong avatar Apr 17 '24 17:04 jijiseong