[javascript] Draft.js에서 텍스트 에디터의 텍스트 감지 및 자동 수정하는 방법

Draft.js는 React 기반의 강력한 텍스트 에디터 라이브러리입니다. 이 라이브러리를 사용하면 사용자가 입력한 텍스트를 쉽게 감지하고, 필요한 경우 자동으로 수정할 수 있습니다. 이번 블로그 포스트에서는 Draft.js를 사용하여 텍스트 감지 및 자동 수정하는 방법에 대해 알아보겠습니다.

텍스트 감지하기

Draft.js에서 사용자가 입력한 텍스트를 감지하려면, onChange 이벤트 핸들러를 사용해야 합니다. 이 핸들러는 사용자가 텍스트를 입력할 때마다 호출됩니다. 이벤트 핸들러에서는 입력된 텍스트를 가져와서 원하는 동작을 수행할 수 있습니다.

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

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

  const handleChange = (newEditorState) => {
    setEditorState(newEditorState);

    // 입력된 텍스트 가져오기
    const contentState = newEditorState.getCurrentContent();
    const text = contentState.getPlainText();

    // 텍스트 감지 및 자동 수정하기
    if (text.includes('바꿀단어')) {
      // 텍스트 수정 로직 작성
      const newText = text.replace('바꿀단어', '새로운단어');

      // 수정된 텍스트 적용하기
      const newContentState = contentState.merge({
        blockMap: contentState.getBlockMap().set(
          contentState.getSelection().getAnchorKey(),
          contentState.getBlockForKey(contentState.getSelection().getAnchorKey()).merge({
            text: newText
          })
        )
      });

      const newEditorState = EditorState.push(newEditorState, newContentState, 'change-block-data');
      setEditorState(newEditorState);
    }
  };

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

export default MyEditor;

위 예제에서는 handleChange 함수에서 입력된 텍스트를 가져와서 text 변수에 할당한 후, 해당 텍스트에 ‘바꿀단어’가 포함되어 있는지 확인한 뒤, ‘바꿀단어’를 ‘새로운단어’로 수정하는 로직을 작성하였습니다.

참고 자료