Published on

Integrate Tiptap with your Next.js project

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Install packages

pnpm install @tiptap/react @tiptap/pm @tiptap/starter-kit

Create Editor Component

// src/app/documents/[documentId]/tiptap-editor.tsx
"use client";

import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";

export const TiptapEditor = () => {
  const editor = useEditor({
    extensions: [StarterKit],
    content: "<p>Hello World! 🌎️</p>",
  });

  return <EditorContent editor={editor} />;
};

Add Nodes, marks, and extensions

Docs: Nodes extensions

生效一个组件包含4个部分

  1. 安装, StarterKit extension包含一些功能, 无需重复安装
  2. 生效css 在src/app/globals.css
  3. 内容样式见useEditor(content)
  4. 配置commands和快捷键

1. Add Task list

  1. install package pnpm install @tiptap/extension-task-list @tiptap/extension-task-item

  2. Css config

    // src/app/globals.css
    .tiptap {
      :first-child {
        margin-top: 0;
      }
    
      /* List styles */
      ul,
      ol {
        padding: 0 1rem;
        margin: 1.25rem 1rem 1.25rem 0.4rem;
    
        li p {
          margin-top: 0.25em;
          margin-bottom: 0.25em;
        }
      }
    
      /* Task list specific styles */
      ul[data-type="taskList"] {
        list-style: none;
        margin-left: 0;
        padding: 0;
    
        li {
          align-items: flex-start;
          display: flex;
    
          > label {
            flex: 0 0 auto;
            margin-right: 0.5rem;
            user-select: none;
          }
    
          > div {
            flex: 1 1 auto;
          }
        }
    
        input[type="checkbox"] {
          cursor: pointer;
        }
    
        ul[data-type="taskList"] {
          margin: 0;
        }
      }
    }
    
  3. enable

    import TaskItem from '@tiptap/extension-task-item'
    import TaskList from '@tiptap/extension-task-list'
    
    export const TiptapEditor = () => {
      const editor = useEditor({
        ...
        extensions: [
          StarterKit,
          TaskList,
          TaskItem.configure({
            nested: true,
          }),
        ],
        content: `
        <ul data-type="taskList">
          <li data-type="taskItem" data-checked="true">A list item</li>
          <li data-type="taskItem" data-checked="false">And another one</li>
        </ul>
      `,
      });
    ...
    }
    
  4. commands or chain

    editor.commands.toggleTaskList()
    // This uses TipTap’s command chaining feature to combine multiple actions into a sequence
    editor.chain().focus().toggleTaskList().run()