[javascript] Draft.js를 이용한 텍스트 에디터의 날짜 및 시간 삽입 기능 구현하기

소개

이번 포스트에서는 Draft.js를 이용하여 텍스트 에디터에 날짜 및 시간을 삽입하는 기능을 구현하는 방법에 대해 알아보겠습니다.

Draft.js란?

Draft.js는 Facebook에서 개발한 오픈소스 리액트 라이브러리로, 텍스트 에디터를 구축하기 위해 사용됩니다. Draft.js는 다양한 텍스트 기능을 지원하며, 커스터마이징이 용이하다는 장점이 있습니다.

구현 방법

  1. Draft.js 패키지를 설치합니다.
npm install draft-js
  1. Draft.js의 Editor 컴포넌트를 생성하고 초기값을 설정합니다.
import React, { useState } from 'react';
import { Editor, EditorState } from 'draft-js';

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

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

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

export default TextEditor;
  1. “삽입” 버튼을 만들고 클릭 이벤트를 처리하는 함수를 작성합니다.
import React, { useState } from 'react';
import { Editor, EditorState, RichUtils, Modifier, convertToRaw } from 'draft-js';

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

  const insertDateTime = () => {
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity('TOKEN', 'IMMUTABLE', {});
    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const currentDate = new Date();

    const formattedDate = currentDate.toLocaleDateString();  // 날짜 포맷 설정
    const formattedTime = currentDate.toLocaleTimeString();  // 시간 포맷 설정

    const newContentState = Modifier.insertText(contentStateWithEntity, contentStateWithEntity.getSelection(), `${formattedDate} ${formattedTime} `, null, entityKey);
    const newEditorState = EditorState.push(editorState, newContentState, 'insert-characters');

    setEditorState(newEditorState);
  }

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

  return (
    <div>
      <Editor editorState={editorState} onChange={onChange} />
      <button onClick={insertDateTime}>삽입</button>
    </div>
  );
}

export default TextEditor;
  1. insertDateTime 함수는 현재 날짜와 시간을 가져와서 에디터 컨텐츠에 삽입하는 역할을 합니다. 삽입된 텍스트는 Draft.js의 Entity로 등록되므로, 렌더링 시에 별도의 스타일을 적용할 수 있습니다.

결론

이렇게 Draft.js를 이용하여 텍스트 에디터에 날짜 및 시간 삽입 기능을 구현할 수 있습니다. Draft.js의 에디터 컴포넌트를 활용하면 다양한 텍스트 관련 기능을 쉽게 구현할 수 있으며, 커스터마이징도 용이합니다.

참고 자료