[javascript] Draft.js로 구현된 에디터를 이용한 댓글 기능 구현하기

이번 포스팅에서는 JavaScript의 라이브러리인 Draft.js를 사용하여 간단한 댓글 기능을 구현하는 방법에 대해 알아보겠습니다. Draft.js는 Facebook에서 개발된 리액트 기반의 텍스트 편집기 라이브러리로, 풍부한 기능과 유연한 사용법으로 널리 사용되고 있습니다.

댓글 에디터 컴포넌트 생성

먼저, Draft.js를 사용하여 댓글을 입력할 수 있는 에디터 컴포넌트를 생성해야 합니다. 이는 일반적인 Draft.js 컴포넌트 생성 방법과 유사하며, 몇 가지 추가 구현 사항이 필요합니다.

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

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

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

  return (
    <div>
      <Editor editorState={editorState} onChange={handleEditorChange} />
    </div>
  );
};

export default CommentEditor;

위 코드에서는 useState 훅을 사용하여 에디터의 상태를 관리합니다. editorState 변수는 에디터의 현재 상태를 나타내며, handleEditorChange 함수를 통해 상태를 업데이트합니다.

댓글 작성 기능 추가

이제 댓글 작성 기능을 추가해보겠습니다. 댓글을 작성할 수 있는 입력 폼과 “댓글 작성” 버튼이 필요합니다. 사용자가 “댓글 작성” 버튼을 클릭하면, 현재 에디터의 내용을 서버로 전송하고 필요한 후속 작업을 수행합니다.

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

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

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

  const handleSubmit = () => {
    const contentState = editorState.getCurrentContent();
    const plainText = contentState.getPlainText();
    
    // 서버로 댓글 정보 전송 및 후속 작업 수행

    // 에디터 초기화
    setEditorState(EditorState.createEmpty());
  };

  return (
    <div>
      <Editor editorState={editorState} onChange={handleEditorChange} />
      <button onClick={handleSubmit}>댓글 작성</button>
    </div>
  );
};

export default CommentEditor;

위 코드에서는 handleSubmit 함수에서 현재 에디터의 내용을 가져와서 서버로 전송하고, 후속 작업을 수행하는 로직을 구현해야 합니다. 이 예제에서는 간략하게 서버로 전송하는 부분만 포함되어 있습니다.

결론

이렇게 Draft.js를 사용하여 댓글 기능을 구현하는 방법에 대해 알아보았습니다. Draft.js의 강력한 기능을 활용하면 텍스트 편집 관련 기능을 쉽게 구현할 수 있으며, 리액트와의 호환성도 좋습니다. 위 예제는 단순한 댓글 기능을 구현한 것이므로, 실제 프로젝트에서는 보안, 인증, 데이터 관리 등 다양한 추가 구현이 필요할 수 있습니다. 이를 참고하여 실제 프로젝트에 적용해보시길 바랍니다.

참고 자료