페블_
반짝이는 시냅스
페블_
전체 방문자
오늘
어제
  • 전체글 보기 (96)
    • QA (0)
    • 프로젝트 회고 (4)
    • 프로젝트 과정 기록 (12)
    • UI 구현 연구일지 (8)
    • Front-end (31)
      • Javascript (7)
      • CSS (10)
      • React (5)
      • Typescript (3)
      • Nextjs (3)
      • 스타일링 라이브러리 (3)
    • Back-end (0)
      • Express (0)
      • DB (0)
    • CS (0)
      • 자료구조 & 알고리즘 (0)
    • CI&CD (1)
    • 툴 사용법 (4)
      • Git (1)
      • Library&패키지 (2)
      • 기타 개발관련 (1)
    • 알고리즘 이론 & 풀이 (36)
      • 백준(BOJ) (14)
      • 프로그래머스 (22)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • JS
  • eslint
  • 캐러셀
  • chartjs
  • 시리즈_표지
  • Python
  • storybook
  • 생각
  • 개발블로그_시작
  • UI 컴포넌트
  • TypeScript
  • react
  • 알고리즘
  • emotion
  • 선형대수학
  • 토이프로젝트
  • 파이썬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
페블_

반짝이는 시냅스

[React] ckEditor5 사용법 및 미리보기 기능 구현
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()로 파싱한 결과값을 넣어주면 될 것이다.

 

 

'Front-end > React' 카테고리의 다른 글

[React] 윈도우 리사이징 예제로 알아보는 throttle  (0) 2023.06.18
[React] React에서 불변성을 지켜야 하는 이유, 불변성이란?  (0) 2023.05.01
[react] Redux 시작하기  (0) 2022.08.28
[React] react-router-dom v6 브라우저 뒤로가기 이벤트 감지 (history.action 대체)  (0) 2022.08.24
    'Front-end/React' 카테고리의 다른 글
    • [React] 윈도우 리사이징 예제로 알아보는 throttle
    • [React] React에서 불변성을 지켜야 하는 이유, 불변성이란?
    • [react] Redux 시작하기
    • [React] react-router-dom v6 브라우저 뒤로가기 이벤트 감지 (history.action 대체)
    페블_
    페블_

    티스토리툴바