[javascript] Draft.js를 사용한 텍스트 에디터의 애니메이션 GIF 추가하기

소개

Draft.js는 React 기반의 오픈 소스 라이브러리로, Rich Text Editor를 구현하기 위한 강력한 도구입니다. 이 글에서는 Draft.js를 사용하여 텍스트 에디터에 애니메이션 GIF를 추가하는 방법에 대해 알아보겠습니다.

애니메이션 GIF 추가하기

텍스트 에디터에 애니메이션 GIF를 추가하기 위해서는 Draft.js 및 관련 모듈을 설치해야 합니다. 아래의 명령을 사용하여 패키지를 설치해주세요.

npm install draft-js react-draft-wysiwyg --save

설치가 완료되었다면, 텍스트 에디터 컴포넌트를 생성하고 필요한 모듈을 import합니다.

import React, { Component } from 'react';
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

애니메이션 GIF를 추가하기 위해서는 Draft.js의 ContentState를 수정해야 합니다. 다음 예제 코드는 ContentState에 이미지 엔티티를 추가하는 함수를 보여줍니다.

const addGif = (editorState, gifUrl) => {
  const contentState = editorState.getCurrentContent();
  const contentStateWithEntity = contentState.createEntity(
    'IMAGE',
    'IMMUTABLE',
    { src: gifUrl }
  );
  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  const newEditorState = EditorState.set(editorState, {
    currentContent: contentStateWithEntity
  });
  return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
};

애니메이션 GIF가 포함된 ContentState를 생성한 후, 텍스트 에디터 컴포넌트에 전달하여 화면에 표시할 수 있습니다.


class MyEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
  }

  handleImageUpload = (file) => {
    // 이미지를 업로드하는 로직을 구현해주세요.
    // 업로드 완료 후, addGif 함수를 호출하여 이미지를 추가합니다.
  };

  render() {
    return (
      <Editor
        editorState={this.state.editorState}
        onEditorStateChange={(editorState) => this.setState({ editorState })}
        toolbar={{
          image: {
            uploadCallback: this.handleImageUpload,
            alt: { present: true, mandatory: true }
          }
        }}
      />
    );
  }
}

위의 코드 예제에서 handleImageUpload 함수를 사용하여 애니메이션 GIF를 업로드하고, addGif 함수를 호출하여 텍스트 에디터에 이미지를 추가하도록 구현해야 합니다. 이 예제에서는 이미지 업로드 로직을 별도로 구현하지 않았으므로, 해당 부분은 직접 구현해야 합니다.

결론

Draft.js를 사용하여 텍스트 에디터에 애니메이션 GIF를 추가하는 방법을 알아보았습니다. 이를 통해 더욱 다양한 컨텐츠를 포함한 리치 텍스트 에디터를 개발할 수 있습니다.

더 자세한 내용은 Draft.js 공식 문서를 참고하세요.