TOAST UI Editor(이하 'TUI 에디터')는 NHN Cloud에서 개발한 오픈 소스 라이브러리로, 마크다운과 위지윅 방식 모두를 지원하는 무료 에디터이다.
npm install @toast-ui/react-editor
import { Editor } from '@toast-ui/react-editor';
import '@toast-ui/editor/dist/toastui-editor.css';
return (
...
<Editor />
...
);
Editor 를 추가하게 되면 나오는 모습이다. 기본적으로
<Editor
previewStyle="vertical"
initialEditType="wysiwyg"
placeholder="글을 작성해 주세요"
height="450px"
toolbarItems={[ ['bold', 'italic', 'strike'],
['hr'],
['image', 'link'],
['ul', 'ol'],
['code', 'codeblock'],
]}
/>
실제 사용한 커스텀이다. 에디터 라이브러리의 가장 큰 장점이라고도 할 수 있는데 , 원하는 기능을 사용하고 필요없는 기능을 제거할 수 있는 것이 가장 큰 장점인 것 같다.
기본적으로 이미지 첨부 기능이 존재하긴 한다 . 하지만 이 경우에 생기는 문제가 있는데 , 바로 base64 인코딩이 되지 않고 첨부되는 모습이다.
// 에디터 ref 설정
<Editor
onChange={() => setContents(editorRef.current.getInstance().getHTML())}
ref={editorRef}
/>
// 이미지 첨부를 위한 코드
useEffect(() => {
if (editorRef.current) {
// 기존 훅 제거
editorRef.current.getInstance().removeHook('addImageBlobHook');
// 새로운 훅 추가
editorRef.current.getInstance().addHook('addImageBlobHook', (blob, callback) => {
(async () => {
let formData = new FormData();
formData.append('image', blob);
console.log('이미지가 업로드 됐습니다.');
await axios.post(`{저장할 서버 api}`, formData, {
header: { 'content-type': 'multipart/formdata' },
withCredentials: true,
});
const imageUrl = '저장된 서버 주소' + blob.name;
setImages([...images, imageUrl]);
callback(imageUrl, 'image');
})();
return false;
});
}
return () => {};
}, [editorRef]);