cantCsharp
cantCsharp

Reputation: 1

Tiptap React-Hook-Form Controller's value in useEditor deps array removes focus on edit

I have a Tiptap editor that is being controlled by React-Hook-Form. Whenever I include value in the second argument (the dependencies array) for useEditor, the editor loses focus whenever I start typing. If I remove value from the dependencies array, the editor keeps its focus, but then my form’s state is not properly synchronized. How can I make this work so that the editor doesn’t lose focus but also stays in sync with the form's value?

interface Props {
    value?: string;
    onChange?: (value: string) => void;
}

const TipTapEditor = ({ value, onChange }: Props) => {
    const editor = useEditor(
        {
            content: cleanText(value || ''),
            onUpdate: ({ editor }) => {
                onChange?.(editor.getHTML());
            },
        },
        [value] // Removing 'value' fixes focus but breaks state sync.
    );
};

export default TipTapEditor;

I use it within a Controller from React-Hook-Form like this:

<Controller
    control={control}
    name="my-name"
    render={({ field: { value, onChange } }) => (
        <TipTapEditor value={value} onChange={onChange} />
    )}
/>

Upvotes: 0

Views: 19

Answers (1)

cantCsharp
cantCsharp

Reputation: 1

Looks like there are some other issues related to this also: https://github.com/ueberdosis/tiptap/discussions/3196

This is how I solved it:

useEffect(() => {
    if (!(editor && value && value !== editor.getHTML())) return

    editor.commands.setContent(value)
}, [value, editor])

Upvotes: 0

Related Questions