아래 포스트에서 비교한 rich text editor 중 react-quill 설치 방법이다.
참고: React용 Rich Text Editor 비교
- https://github.com/zenoamaro/react-quill 여기서 npm이나 yarn으로 설치한다.
$yarn add react-quill
$yarn add quill-image-upload // 이미지 업로드용 유틸리티
그리고 Editor를 사용할 component에 로드한다.
import ReactQuill, { Quill } from 'react-quill';
import { ImageUploader } from 'quill-image-upload';
import 'react-quill/dist/quill.snow.css';
Quill.register('modules/imageUpload', ImageUpload); // 커스텀 라이브러리를 등록해 준다.
- 설정 파일에 quill을 전역 변수로 등록한다.
사실 전역을 건드리는 건 피하고 싶은데 조사한 대부분의 rich text editor가 전역 변수로 설정해서 사용한다.
react-rewired 설정파일에 아래 설정을 등록한다.
참고: react eject는 그만 react rewired 사용방법 feat. mobx
config-overrides.js
module.exports = function override(config, env) {
config = rewireProvidePlugin(config, env, {
'window.Quill': ['react-quill', 'Quill']
})
return config;
}
- toolbar를 설정한다.
modules = {
toolbar: {
container: [
[{ 'header': '1'}, {'header': '2'}, { 'font': [] }],
[{size: []}],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'},
{'indent': '-1'}, {'indent': '+1'}],
['link', 'image', 'video']
],
// container: [['bold', 'italic', 'underline', 'blockquote'],
// [{'list': 'ordered'}, {'list': 'bullet'}],
// ['formula','link', 'image'],
// ['clean']],
// handlers: { 'image' : this.handleImage }
},
imageUpload: {
url: "<내 image upload API 주소>", // server url
method: "POST", // change query method, default 'POST'
name : 'images' // 아래 설정으로 image upload form의 key 값을 변경할 수 있다.
headers: {
Authorization: `Bearer ${<내 토큰 값>}`,
'X-Total-Count': 0,
},
callbackOK: (serverResponse, next) => { // 성공하면 리턴되는 함수
next(serverResponse);
},
callbackKO: (serverError) => { // 실패하면 리턴되는 함수
console.log(serverError);
// alert(serverError);
},
// optional
// add callback when a image have been chosen
checkBeforeSend: (file, next) => {
console.log(file);
next(file); // go back to component and send to the server
}
},
clipboard: {
// toggle to add extra line breaks when pasting HTML:
matchVisual: false,
},
// imageDrop: true, // imageDrop 등록
// imageResize: {} // imageResize 등록
}
- format을 설정한다.
formats = [
'header', 'font', 'size',
'bold', 'italic', 'underline', 'strike', 'blockquote',
'list', 'bullet', 'indent',
'link', 'image', 'video'
]
- handler를 설정한다.
changeEditor = e => this.setState({ body: e });
- Component를 호출한다.
< ReactQuill
ref={(el) => this.quillRef = el}
value={this.state.body} // state 값
theme="snow" // 테마값 이미 snow.css를 로드해서 제거해도 무망
onChange={this.changeEditor}
modules={this.modules}
formats={this.formats}
placeholder={'아무거나 입력해 주세요'}
/>'
- 기본적으로 이미지는 image 라는 키 값으로 등록된다.
이 값을 바꿔주기 위해서는 quill-image-upload 설정값을 바꿔줘야 한다.
node_modules 에서 quill-image-upload 디렉터리를 찾는다.
index.js 파일 수정
58번째줄 부터 아래와 같이 수정
sendToServer(file) {
const url = this.options.url || 'your-url.com',
method = this.options.method || 'POST',
name = this.options.name || 'image', // add
headers = this.options.headers || {},
callbackOK = this.options.callbackOK || this.uploadImageCallbackOK.bind(this),
callbackKO = this.options.callbackKO || this.uploadImageCallbackKO.bind(this),
fd = new FormData();
// fd.append('image', file); // remove
fd.append(name, file); // add
const xhr = new XMLHttpRequest();
// init http query
xhr.open(method, url, true);
// add custom headers
for (var index in headers) {
xhr.setRequestHeader(index, headers[index]);
}
// listen callback
xhr.onload = () => {
if (xhr.status === 201) { // API response 값에 따라 201로 수정
callbackOK(JSON.parse(xhr.responseText), this.insert.bind(this));
} else {
callbackKO({
code: xhr.status,
type: xhr.statusText,
body: xhr.responseText
});
}
};
xhr.send(fd);
}
이 외에 쓸만한 유틸리티
- https://github.com/kensnyder/quill-image-drop-module : 드래그엔 드롭으로 이미지 추가 가능 (ajax upload 불가)
- https://github.com/kensnyder/quill-image-resize-module : resize 모듈