React-Quill 사용법

안녕하세요·2024년 5월 9일
0

react

목록 보기
26/32
npm install react-quill

CSS 임포트

React-Quill은 스타일링을 위해 Quill의 CSS를 필요로 합니다. 이 CSS 파일은 패키지 설치 시 함께 제공되므로, 프로젝트에서 직접 임포트해야 합니다.

import 'react-quill/dist/quill.snow.css'; // Snow 테마 CSS

React-Quill 컴포넌트 사용

컴포넌트 임포트: React-Quill 컴포넌트를 임포트합니다.

import ReactQuill, { Quill } from 'react-quill';

에디터 상태 관리

useState를 사용하여 에디터의 현재 상태를 관리합니다

const [value, setValue] = useState('');

에디터 설정

Quill 에디터에 사용할 모듈과 포맷을 설정합니다. useMemo를 사용하여 컴포넌트가 리렌더링될 때마다 설정이 재생성되는 것을 방지합니다.

const modules = useMemo(() => ({
    toolbar: {
        container: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'], // blocks
            [{ 'header': 1 }, { 'header': 2 }], // custom button values
            [{ 'list': 'ordered'}, { 'list': 'bullet' }], // lists
            [{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
            [{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
            [{ 'direction': 'rtl' }], // text direction
            [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }], // dropdown with defaults
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['image', 'video', 'clean'] // remove formatting button
        ],
        handlers: { image: imageHandler }
    },
    imageDrop: true,
    imageResize: {}
}), []);

에디터 렌더링

ReactQuill 컴포넌트를 사용하여 에디터를 렌더링합니다. ref, theme, value, onChange, modules, 및 formats 속성을 설정합니다.

이미지 처리 핸들러

사용자가 이미지를 에디터에 삽입할 수 있도록 이미지 업로드와 관련된 로직을 구현합니다

const imageHandler = () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();

    input.addEventListener('change', async () => {
        const file = input.files[0];
        const formData = new FormData();
        formData.append('img', file);
        try {
            let IMG_URL = await imageUpload(file);
            const editor = quillRef.current.getEditor();
            const range = editor.getSelection();
            editor.insertEmbed(range.index, 'image', `${process.env.REACT_APP_SERVER_URL}${IMG_URL}`);
        } catch (error) {
            console.error('Image upload failed:', error);
        }
    });
};

0개의 댓글