[javascript] Draft.js를 이용한 텍스트 에디터의 테이블 삽입 기능 구현하기

이번 블로그 포스트에서는 Draft.js를 이용하여 텍스트 에디터에 테이블 삽입 기능을 구현하는 방법에 대해 알아보겠습니다. 테이블은 문서 작성 시 표 형태로 정보를 나타내는데 유용하게 사용됩니다.

Draft.js란?

Draft.js는 Facebook에서 개발한 오픈 소스 라이브러리로, 웹 기반의 WYSIWYG 텍스트 에디터를 만들기 위해 사용됩니다. React 기반으로 작성되었으며, 복잡한 에디터 기능을 쉽게 구현할 수 있도록 도와줍니다. 특히, Rich Text Editor의 구현을 위해 사용되는 경우가 많습니다.

테이블 삽입 기능 구현하기

테이블 삽입 기능을 구현하기 위해 먼저 Draft.js의 ContentState에 테이블 정보를 저장하는 방법을 고려해야 합니다. ContentState는 Draft.js에서 사용되는 텍스트의 상태를 나타내는 객체입니다.

const insertTable = (editorState) => {
  const contentState = editorState.getCurrentContent();
  const selectionState = editorState.getSelection();

  const tableRows = 3; // 테이블에 추가할 행의 개수
  const tableCols = 3; // 테이블에 추가할 열의 개수

  const newContentState = Modifier.insertText(
    contentState,
    selectionState,
    " "
  );

  let tableText = "";
  for (let row = 0; row < tableRows; row++) {
    for (let col = 0; col < tableCols; col++) {
      tableText += "| |";
    }
    tableText += "\n";
  }

  const updatedContentState = Modifier.insertText(
    newContentState,
    newContentState.getSelectionAfter(),
    tableText
  );

  const newEditorState = EditorState.push(
    editorState,
    updatedContentState,
    "insert-table"
  );

  return EditorState.forceSelection(
    newEditorState,
    updatedContentState.getSelectionAfter()
  );
}

위의 예시 코드는 insertTable 함수를 통해 테이블을 삽입하는 기능을 구현한 코드입니다. tableRowstableCols 변수를 통해 테이블에 추가할 행과 열의 개수를 설정할 수 있습니다.

기능 적용하기

테이블 삽입 기능을 텍스트 에디터에 적용하려면, Draft.js를 초기화하고 테이블 삽입 버튼에 insertTable 함수를 연결해야 합니다.

import React, { useState } from "react";
import { Editor, EditorState, RichUtils } from "draft-js";

const TextEditor = () => {
  const [editorState, setEditorState] = useState(() =>
    EditorState.createEmpty()
  );

  const handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      setEditorState(newState);
      return "handled";
    }
    return "not-handled";
  };

  const handleInsertTable = () => {
    const newEditorState = insertTable(editorState);
    setEditorState(newEditorState);
  };

  return (
    <div>
      <button onClick={handleInsertTable}>테이블 삽입</button>
      <div>
        <Editor
          editorState={editorState}
          handleKeyCommand={handleKeyCommand}
          onChange={setEditorState}
        />
      </div>
    </div>
  );
}

export default TextEditor;

위의 예시 코드에서는 handleInsertTable 함수를 테이블 삽입 버튼에 연결하여 테이블 삽입 기능을 호출하도록 구현되었습니다. 이제 TextEditor 컴포넌트를 사용하여 원하는 곳에 텍스트 에디터를 삽입할 수 있습니다.

마치며

이번 포스트에서는 Draft.js를 이용하여 텍스트 에디터에 테이블 삽입 기능을 구현하는 방법을 알아보았습니다. 테이블 삽입 기능은 문서 작성 시 효과적으로 정보를 표현하기 위해 꼭 필요한 기능입니다. 이를 통해 사용자들은 보다 편리하고 효율적인 문서 작성 환경을 만들 수 있습니다.

Draft.js에 대한 자세한 내용은 공식 문서를 참고하시기 바랍니다.