reactjsnext.jsreact-hook-formtiptap

How to Use React Hook Form with TipTap Editor


I have text input using react hook form like this

        <div className='mb-4'>
                                <label htmlFor='desc'>Description</label>
                                <TipTap 
                                
                                // iwant to pass the  ...regiseter props here
                                
                                />

                                <textarea
                                    className='w-full'
                                    id='desc'
                                    autoFocus
                                    {...register('desc', {
                                        required: 'Please enter description',
                                    })}
                                />
                                {errors.desc && (
                                    <div className='text-red-500'>{errors.desc.message}</div>
                                )}
                            </div>

and here is my Tiptap Component

const TipTap = () => {
    const tipTapEditor = useEditor({
        extensions: [StarterKit],
        content: ``,
        onUpdate: ({ editor }: any) => {
            const html = editor.getHTML();
            console.log(html);
        },
    });

    return (
        <div>
            <MenuBar editor={tipTapEditor} />
            <EditorContent editor={tipTapEditor} />
        </div>
    );
};

I want to use Tiptap editor how i can pass the {...register} as props to the TitaTap compenent


Solution

  • I would recommend using the component or useController hook from RHF.

    const DocumentController: React.FC<DocumentControllerProps> = ({
      name,
      required = false,
      readOnly = false,
    }) => {
      const {
        field: { onChange, value, ref },
      } = useController({
        name,
        rules: { required },
      });
      return (
        <TipTapComponent
          initialValue={value}
          readOnly={readOnly}
          onChange={onChange}
        />
      );
    };
    

    and in your tiptap component,

    const TipTap = ({ initialValue, onChange }) => {
      const tipTapEditor = useEditor({
        extensions: [StarterKit],
        content: initialValue,
        onUpdate: ({ editor }) => {
          const html = editor.getHTML();
          onChange(html);
        },
      });
    
      return (
        <div>
          <MenuBar editor={tipTapEditor} />
          <EditorContent editor={tipTapEditor} />
        </div>
      );
    };