[javascript] Draft.js에서 텍스트 에디터의 탭 기능 추가하기

소개

Draft.js는 React 기반의 텍스트 에디터 라이브러리로, 강력한 기능과 유연성을 제공합니다. 이 라이브러리를 사용하여 커스텀 텍스트 에디터를 개발할 수 있습니다. 이번 글에서는 Draft.js에서 텍스트 에디터에 탭 기능을 추가하는 방법을 알아보겠습니다.

탭 기능 구현하기

  1. Draft.js 설치하기
    npm install draft-js
    
  2. Draft.js 에디터 컴포넌트 생성하기
    import React, { Component } from 'react';
    import { Editor, EditorState, getDefaultKeyBinding, KeyBindingUtil } from 'draft-js';
    
    class MyEditor extends Component {
      constructor(props) {
        super(props);
        this.state = {
          editorState: EditorState.createEmpty()
        };
      }
    
      handleKeyCommand = (command, editorState) => {
        if (command === 'tab') {
          // 탭 기능 구현 로직 추가
          return 'handled';
        }
        return 'not-handled';
      }
    
      keyBindingFn = (event) => {
        if (KeyBindingUtil.hasCommandModifier(event) && event.keyCode === 9) {
          return 'tab';
        }
        return getDefaultKeyBinding(event);
      }
    
      onChange = (editorState) => {
        this.setState({ editorState });
      }
    
      render() {
        return (
          <Editor
            editorState={this.state.editorState}
            handleKeyCommand={this.handleKeyCommand}
            keyBindingFn={this.keyBindingFn}
          />
        );
      }
    }
    
    export default MyEditor;
    
  3. 탭 기능 구현하기
    handleKeyCommand = (command, editorState) => {
      if (command === 'tab') {
        const contentState = editorState.getCurrentContent();
        const selectionState = editorState.getSelection();
    
        if (!selectionState.isCollapsed()) {
          const newContentState = Modifier.insertText(contentState, selectionState, '\t');
          const newEditorState = EditorState.push(editorState, newContentState, 'insert-characters');
          this.setState({ editorState: newEditorState });
          return 'handled';
        }
      }
    
      return 'not-handled';
    }
    

위의 코드는 Draft.js 에디터 컴포넌트 내부에 탭 기능을 추가하는 방법을 보여주고 있습니다. handleKeyCommand 메소드는 commandeditorState 파라미터를 받으며, 탭 키 입력이 감지되면 선택된 텍스트가 있는 경우에만 탭 문자(‘\t’)를 삽입합니다.

결론

Draft.js에서 텍스트 에디터에 탭 기능을 추가하는 방법을 알아보았습니다. 이를 활용하여 더 풍성한 사용자 경험을 제공하는 텍스트 에디터를 개발할 수 있습니다. 추가로 필요한 기능을 구현하거나 더 자세한 내용을 알아보고 싶다면, Draft.js 공식 문서를 참고하시기 바랍니다.