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

이번 포스트에서는 React의 대표적인 WYSIWYG 에디터 라이브러리인 Draft.js를 사용하여 라벨링 기능을 구현하는 방법에 대해 알아보겠습니다.

Draft.js란?

Draft.js는 Facebook에서 개발한 오픈 소스 WYSIWYG 에디터 라이브러리입니다. React 기반으로 구축되어 있어서 React 애플리케이션에서 쉽게 사용할 수 있습니다. Draft.js는 커스터마이징이 가능하고 풍부한 기능을 제공하여 다양한 에디터 요구를 충족시켜줍니다.

구현 방법

먼저, 프로젝트에 Draft.js를 설치합니다.

npm install draft-js

다음은 라벨링 기능을 추가한 에디터 컴포넌트의 코드 예시입니다.


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

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

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

  const onLabelButtonClick = () => {
    const newEditorState = RichUtils.toggleInlineStyle(editorState, 'LABEL');
    setEditorState(newEditorState);
  };

  const labelStyle = {
    backgroundColor: '#ff9900',
    color: '#fff',
    padding: '2px',
    borderRadius: '4px',
    fontWeight: 'bold',
  };

  const labelStrategy = (contentBlock, callback) => {
    contentBlock.findStyleRanges(character => {
      const style = character.getStyle();
      return style.has('LABEL');
    }, callback);
  };

  const LabelSpan = props => (
    <span {...props} style={labelStyle} />
  );

  return (
    <div>
      <button onClick={onLabelButtonClick}>라벨링</button>
      <Editor
        editorState={editorState}
        handleKeyCommand={handleKeyCommand}
        customStyleMap={{ LABEL: labelStyle }}
        blockStyleFn={contentBlock => {
          const type = contentBlock.getType();
          if (type === 'unstyled') {
            return 'paragraph';
          }
        }}
        customStyleFn={style => {
          if (style.has('LABEL')) {
            return labelStyle;
          }
        }}
        decorators={[
          {
            strategy: labelStrategy,
            component: LabelSpan,
          },
        ]}
        onChange={setEditorState}
      />
    </div>
  );
};

export default LabellingEditor;

위의 코드를 살펴보면, LabellingEditor 컴포넌트가 Draft.js의 Editor 컴포넌트를 사용하여 라벨링 기능을 구현하고 있습니다.

handleKeyCommand 함수는 키보드 명령을 처리하는 역할을 합니다. RichUtils.handleKeyCommand 함수를 사용하여 키보드 명령을 처리하고, 새로운 에디터 상태를 업데이트합니다.

onLabelButtonClick 함수는 라벨링 버튼이 클릭될 때마다 RichUtils.toggleInlineStyle 함수를 사용하여 현재 선택된 텍스트에 ‘LABEL’ 스타일을 토글합니다.

labelStrategy 함수는 에디터 내에서 ‘LABEL’ 스타일을 적용한 텍스트를 찾기 위한 전략을 정의합니다.

LabelSpan 컴포넌트는 ‘LABEL’ 스타일이 적용된 텍스트를 렌더링하는 역할을 합니다.

이렇게 구현된 LabellingEditor 컴포넌트를 필요한 곳에서 사용하여 라벨링 기능을 적용할 수 있습니다.

마무리

이번 포스트에서는 Draft.js를 사용하여 라벨링 기능을 구현하는 방법에 대해 알아보았습니다. Draft.js의 다양한 기능을 활용하여 원하는 에디터를 만들 수 있으니 많은 활용 부탁드립니다.

참고: Draft.js 공식 문서