반응형

npm

$ npm install --save react-editor-js @editorjs/editorjs
$ npm install --save @editorjs/header
$ npm install --save @editorjs/list
$ npm install --save @editorjs/code
$ npm install --save @editorjs/paragraph
$ npm install --save @editorjs/checklist

 

editorTools.js

editor를 정의해줄 내용이 없기 때문에 editorTools부분은 js로 작성했습니다.

// import Code from "@editorjs/code";
import Header from "@editorjs/header";
import Paragraph from "@editorjs/paragraph";
import List from "@editorjs/list";
// import CheckList from "@editorjs/checklist";

export const EDITOR_TOOLS = {
    header: {
        class: Header,
        inlineToolbar: true,
        shortcut: "CMD+SHIFT+H"
    },
    paragraph: { class: Paragraph, inlineToolbar: true },
    list: {
        class: List,
        inlineToolbar: true
    }
};

 

tsconfig.json

js를 사용했기 때문에 아래처럼 include부분에 js를 사용했다고 알려주었습니다.

"include": ["src/components/editor/editorTools.jss.js"]

 

editor.tsx

import React, { memo, useEffect, useRef } from "react";
import EditorJS, { OutputData } from "@editorjs/editorjs";
import { EDITOR_TOOLS } from "./EditorTools";

//props
type Props = {
  data?: OutputData;
  onChange(val: OutputData): void;
  holder: string;
};

const EditorBlock = ({ data, onChange, holder }: Props) => {
  // 참조 추가
  const ref = useRef<EditorJS>();

  // 초기화
  useEffect(() => {
    // 참조가 없을때 초기화 합니다.
    if (!ref.current) {
      const editor = new EditorJS({
        holder: holder,
        tools: EDITOR_TOOLS,
        data,
        async onChange(api, event) {
          const data = await api.saver.save();
          onChange(data);
        },
      });
      ref.current = editor;
    }

    return () => {
      if (ref.current && ref.current.destroy) {
        ref.current.destroy();
      }
    };
  }, []);


  return <div id={holder} />;
};

export default memo(EditorBlock);

 

index.tsx

import dynamic from "next/dynamic";
import { OutputData } from '@editorjs/editorjs';

const EditorBlock = dynamic(() => import("@/components/editor/editor"), { ssr: false });

const Page = () => {
    
    const [data, setData] = useState<OutputData>();
    
    return (
        <EditorBlock data={data} onChange={setData} holder="editorjs-container" />
    );
}

export default Page;

 

반응형

+ Recent posts