글쓰기 페이지 기능을 구현해 보자.

Untitled

25-1. 에디터 UI 구현하기


글을 작성하는 에디터는 ‘Quill'이라는 라이브러리를 사용한다.

$ npm i quill

제목과 내용을 입력할 수 있는 Editor 컴포넌트를 만든다.

import styled from "styled-components";
import Responsive from "../common/Responsive";
import palette from "../../lib/styles/palette";
import {useEffect, useRef} from "react";
import Quill from "quill/quill";
import 'quill/dist/quill.bubble.css';

const EditorBlock = styled(Responsive)`
  /* 위아래 여백 지정 */
  padding-top: 5rem;
  padding-bottom: 5rem;
`;

const TitleInput = styled.input`
	font-size: 3rem;
  outline: none;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid ${palette.gray[4]};
  margin-bottom: 2rem;
  width: 100%;
`;

const QuillWrapper = styled.div`
  /* 최소 크기 지정 및 padding 제거 */
  .ql-editor {
    padding: 0;
    min-height: 320px;
    font-size: 1.125rem;
    line-height: 1.5;
  }

  .ql-editor.ql-blank::before { /* 실제 내용 바로 앞에서 생성되는 자식 요소 */
    left: 0px;
  }
`;

const Editor = () => {
    const quillElement = useRef(null); // Quill을 적용할 DivElement를 설정
    const quillInstance = useRef(null); // Quill 인스턴스를 설정

    useEffect(() => {
        quillInstance.current = new Quill(quillElement.current, {
            theme: 'bubble',
            placeholder: '내용을 작성하세요.',
            modules: {
                toolbar: [
                    [{header: '1'}, {header: '2'}],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{list: 'ordered'}, {list: 'bullet'}],
                    ['blockquote', 'code-block', 'link', 'image'],
                ],
            },
        });
    }, []);

    return (
        <EditorBlock>
            <TitleInput/>
            <QuillWrapper>
                <div ref={quillElement}/>
            </QuillWrapper>
        </EditorBlock>
    );
};

export default Editor;

: 이처럼, 외부 라이브러리를 연동할 때는 useRefuseEffect를 적절하게 사용하면 된다.