Front-end/React

[React] ckEditor5 사용법 및 미리보기 기능 구현

페블_ 2023. 6. 29. 20:30

구현 결과

설치

npm install --save @ckeditor/ckeditor5-react @ckeditor/ckeditor5-build-classic

react를 위한 ckeditor 패키지를 설치하고, 여러 버전 중 classic Editor를 구현할 것이므로 classic을 설치

 

 

ckeditor 화면에 띄우기

css로 에디터 크기를 지정해주지 않으면 화면에 넙대대하게 나온다.

ckeditor.css

css 설정

/* ----------------------------------- */
/* CKEditor 크기 조정                    */
/* ----------------------------------- */

/* 텍스트입력태그 */
.ck.ck-editor__editable:not(.ck-editor__nested-editable) {
  min-height: 600px;
  margin-bottom: 30px;
}

/* 입력내용이 짧고 행이 길어지면 자동으로 텍스트입력태그 가로넓이가 줄어들기 때문에 고정 */
.ck-editor__editable_inline {
  width: 700px;
}

 

App.tsx

import './ckeditor.css';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
const [content, setContent] = useState('');

return (
    <CKEditor
      editor={ClassicEditor}
      data=""
      onReady={(editor) => {
        // You can store the "editor" and use when it is needed.
        console.log('Editor is ready to use!', editor);
      }}
      onChange={(event, editor) => {
        const data = editor.getData();
        setContent(data);
        console.log('content', content);
        console.log('onChange', { event, editor, data });
      }}
      // // onBlur: focus가 해제되었을 때
      // onBlur={(event, editor) => {
      //   console.log('Blur.', editor);
      // }}
      // // onFocus: editor에 focus가 감지되었을 때
      // onFocus={(event, editor) => {
      //   console.log('Focus.', editor);
      // }}
    />
  );

주석처리한 곳(onBlur, onFocus)은 focus 이벤트와 관련 된 것이므로 필요없으면 삭제해도 된다.

 

미리보기 구현 (html-react-parser)

글을 입력하면 <p>내용1</p><p>내용2</p> 이렇게 줄줄이 하나의 문자열 형태로 값이 저장되는데,

이를 해석해 화면에 띄워주려면 html parser가 필요하다.

 

설치

npm install html-react-parser

(유사한 라이브러리로 react-html-parser가 있는데 얘는 react 18 버전과 충돌이 일어나서 html-react-parser를 쓰는 게 좋다)

 

  • parse를 라이브러리로부터 import하고 parse(내용) 으로 호출해서 사용한다.
  • 화면이 너무 복잡해서 ckEditor를 Editor라는 컴포넌트로 따로 분리하고, pros로 content와 setContent를 내려줬다.
  • 미리보기는 <div>를 하나 만들고 그 아래에 parse(content) 한 결과값을 집어넣어주면 된다.
import React, { useState } from 'react';
import { css } from '@emotion/react';
import parse from 'html-react-parser';
import './ckeditor.css';
import Editor from './components/Editor';

function App() {
  const [content, setContent] = useState('');

  return (
    <div css={wrapperStyle}>
      <div>
        <h2>Using CKEditor 5 build in React</h2>
        <Editor content={content} setContent={setContent} />
      </div>
      <div css={previewBoxStyle}>{parse(content)}</div>
    </div>
  );
}

const wrapperStyle = css`
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 50px;
  padding-top: 50px;
`;

const previewBoxStyle = css`
  max-width: 700px;
`;

export default App;

 

ckeditor를 커스텀하며 기능이 잘 되는지 테스트할 때 편하라고 옆에 미리보기 창을 만들어봤다.

만약 글 작성 버튼을 누르기 전 미리보기를 모달로 띄우고 싶거나 하면, 모달창에 parse()로 파싱한 결과값을 넣어주면 될 것이다.