React 프로젝트에 TOAST UI Editor를 통합하기 전에, 필요한 npm 패키지들을 설치해야 합니다. 다음 명령어를 사용하여 설치할 수 있습니다
npm install @toast-ui/react-editor
npm install @toast-ui/editor-plugin-color-syntax
이 명령어는 TOAST UI Editor의 React 래퍼와 색상 선택 기능을 제공하는 플러그인을 설치합니다.
에디터를 React 컴포넌트에 통합하기 위해 필요한 모듈을 임포트합니다. 또한, 에디터와 관련된 CSS 파일들을 포함시켜 스타일을 적용합니다:
import React, { useRef, useState } from 'react';
import { Editor } from '@toast-ui/react-editor';
import '@toast-ui/editor/dist/toastui-editor.css';
import colorSyntax from '@toast-ui/editor-plugin-color-syntax';
import '@toast-ui/editor-plugin-color-syntax/dist/toastui-editor-plugin-color-syntax.css';
useRef를 사용하여 에디터의 인스턴스를 참조하고, useState를 사용하여 에디터의 내용을 관리합니다. 에디터 컴포넌트를 JSX에 포함시키고, 초기값, 편집 타입, 플러그인 등을 설정합니다
const editorRef = useRef(null);
const [content, setContent] = useState('Hello React Editor World!');
<Editor
initialValue={content}
previewStyle="vertical"
height="600px"
initialEditType="markdown"
useCommandShortcut={false}
plugins={[colorSyntax]}
language="ko-KR"
ref={editorRef}
onChange={onChange}
hooks={{
addImageBlobHook: onUploadImage
}}
/>
이미지를 업로드할 때 사용할 addImageBlobHook을 구현하여, 드래그 앤 드롭 또는 클립보드를 통해 추가된 이미지를 처리합니다. 이 훅은 이미지 파일을 서버로 전송하고, 반환된 이미지 URL을 에디터에 삽입합니다
const onUploadImage = async (blob, callback) => {
let imgPath = await imageUpload(blob);
callback(process.env.REACT_APP_SERVER_URL+imgPath, 'alt text');
return false;
};
TOAST UI Viewer를 사용하여 사용자가 입력한 마크다운 콘텐츠를 HTML로 변환하여 보여줍니다. Viewer 컴포넌트는 초기값으로 HTML 콘텐츠를 받아서 렌더링합니다.
<Viewer initialValue={data} />