[javascript] Draft.js를 이용한 텍스트 에디터의 스레드(Thread) 기능 구현하기

소개

이번 포스트에서는 Draft.js를 이용하여 텍스트 에디터에 스레드 기능을 구현하는 방법을 알아보겠습니다. 스레드 기능은 사용자들이 특정 부분에 대한 응답이나 댓글을 작성할 수 있는 기능을 제공합니다. Draft.js는 JavaScript로 작성된 리액트 기반의 강력한 텍스트 에디터 라이브러리로, 여러분이 원하는 대로 커스터마이즈할 수 있습니다.

준비물

이 예제를 따라하기 위해서는 다음과 같은 것들이 필요합니다:

프로젝트 설정

먼저 React 프로젝트를 생성하고 Draft.js를 설치해야 합니다. 아래의 커맨드를 터미널이나 명령 프롬프트에서 실행하여 React 프로젝트를 생성하세요.

npx create-react-app thread-editor

프로젝트 생성이 완료되면 cd thread-editor으로 생성된 프로젝트 폴더로 이동한 후, Draft.js를 설치합니다.

npm install draft-js

스레드 컴포넌트 작성

Draft.js를 사용하여 스레드 기능을 구현하기 위해 스레드 컴포넌트를 작성해야 합니다. 스레드 컴포넌트는 사용자가 댓글을 작성할 수 있는 영역을 표시하고 관리하는 역할을 합니다.

먼저, Editor.js라는 새로운 컴포넌트 파일을 생성하고 아래의 코드를 추가합니다.

import React, { useState, useRef } from 'react';
import { Editor, EditorState, RichUtils, getDefaultKeyBinding, KeyBindingUtil } from 'draft-js';
import 'draft-js/dist/Draft.css';

const EditorThread = () => {
  const [editorState, setEditorState] = useState(() => EditorState.createEmpty());
  const editorRef = useRef(null);

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

  const keyBindingFn = (event) => {
    if (KeyBindingUtil.hasCommandModifier(event) && event.keyCode === 83) {
      return 'save';
    }
    return getDefaultKeyBinding(event);
  };

  const onEditorChange = (newEditorState) => {
    setEditorState(newEditorState);
  };

  const handleSave = () => {
    // 댓글 저장 로직 추가
  };

  return (
    <div>
      <div>
        <Editor
          editorState={editorState}
          onChange={onEditorChange}
          handleKeyCommand={handleKeyCommand}
          keyBindingFn={keyBindingFn}
          placeholder="댓글을 작성하세요"
          ref={editorRef}
        />
      </div>
      <button onClick={handleSave}>댓글 저장</button>
    </div>
  );
};

export default EditorThread;

위의 코드는 Draft.js의 Editor 컴포넌트를 사용하여 스레드를 구현합니다. EditorThread 컴포넌트는 editorState 상태와 setEditorState 함수를 통해 에디터의 상태를 관리합니다. handleKeyCommand 함수는 단축키를 처리하기 위해 사용되며, keyBindingFn 함수는 사용자가 특정 키를 눌렀을 때 해당 단축키를 처리하기 위해 사용됩니다. onEditorChange 함수는 에디터의 내용이 변경되었을 때 호출되며, handleSave 함수는 댓글 저장 로직을 추가할 곳입니다.

메인 앱 컴포넌트에 스레드 컴포넌트 추가

이제 작성한 스레드 컴포넌트를 메인 앱 컴포넌트에 추가해봅시다. App.js 파일을 열고 아래의 코드를 추가합니다.

import React from 'react';
import EditorThread from './Editor';

const App = () => {
  return (
    <div className="App">
      <h1>스레드 기능을 갖는 텍스트 에디터</h1>
      <EditorThread />
    </div>
  );
};

export default App;

위의 코드는 EditorThread 컴포넌트를 메인 앱 컴포넌트에 추가하여 화면에 렌더링합니다.

실행 및 테스트

React 프로젝트 폴더에서 다음 커맨드를 실행하여 앱을 실행해보세요.

npm start

브라우저에서 http://localhost:3000으로 접속하면 스레드 기능을 갖는 텍스트 에디터가 나타납니다. 댓글을 작성하고 “댓글 저장” 버튼을 클릭하여 저장 기능을 확인해보세요.

마무리

이번 포스트에서는 Draft.js를 이용하여 텍스트 에디터에 스레드 기능을 구현하는 방법을 알아보았습니다. Draft.js는 많은 커스터마이즈가 가능한 텍스트 에디터 라이브러리로, 다양한 기능을 추가하여 사용자 정의 에디터를 만들 수 있습니다.