HomePoststiptap onEnterPress

How to add onKeyPress to TipTap in React

Date
Last Updated
Profile Picture
Peter White@petewht

At Graphy, we use TipTap as our rich text WYSIWYG editor.

A common request is that the user can submit their content when they press enter.

This is easy for a simple HTML text area:

<textarea onkeypress="onEnterFunction();"></textarea>

However, TipTap doesn't have an onKeyPress event. Instead, we'll need to make a custom extension that intercepts the enter key and runs a callback:

import { Extension } from '@tiptap/core';
 
export const interceptNewline = (callback: () => void) => {
  return Extension.create({
    name: 'interceptNewline',
 
    addKeyboardShortcuts() {
      return {
        Enter: () => {
          callback();
          return true;
        },
      };
    },
  });
};

Then, in your editor config, use the extension and pass in your submit function:

const editor = useEditor({
  extensions: [interceptNewline(yourFunctionHere)],
});

Now when the user presses enter, your callback will be run!


Thanks for Reading!

I always appreciate feedback or suggestions for future blog posts. You can find me on Twitter or if you want to improve the article to help future readers, please feel free to submit a PR.

🦉 2570 days

Duolingo Streak

Proudly created in beautiful Sætre in Norway 🇳🇴