라이브러리/SunEditor-react

[suneditor-react] suneditor 사용법

눙엉 2022. 11. 19. 18:28

suneditor-react

🔍 해당 라이브러리를 선택한 이유

1. 글 좌우 정렬

2. 폰트 변경

3. 이미지 첨부

4. 텍스트 컬러 변경

 

위 4가지가 필요한 기능이었다.

 

많이 사용한다고 들었던 TOAST UI Editor를 사용하려 했으나 1번 요구사항이 만족하지 못해 다른 editor를 찾아보게 되었다.

여러 에디터가 존재했지만 해당 sundeditor는 위의 모든 요구사항을 충족하고, issue를 등록하면 빠르게 대답해주어서 맘에 들었다.

 

🔍 설치 및 버전

$ npm install --save suneditor suneditor-react
"suneditor": "^2.44.3",
"suneditor-react": "^3.4.1",

 

🔍 초기 렌더링

suneditor 렌더링

import React, { useRef } from "react";
import SunEditor from "suneditor-react";
import SunEditorCore from "suneditor/src/lib/core";
import "suneditor/dist/css/suneditor.min.css";

const Editor = () => {
  const editor = useRef<SunEditorCore>();

  const getSunEditorInstance = (sunEditor: SunEditorCore) => {
    editor.current = sunEditor;
  };

  return <SunEditor getSunEditorInstance={getSunEditorInstance} />
};

export default Editor;

 

🔍 옵션

사용해보았던 옵션들만 정리했습니다. (이 외의 옵션은 해당 라이브러리 README에서 확인 가능합니다)

 

buttonList

라이브러리 내에서 지정해둔 버튼 모음들과 커스텀으로 설정하는 2가지 방법이 있다.

 

지정해둔 버튼 모음으로는 3가지 종류가 있다. 

 

  • basic (워드 프로세싱을 위한 기본 버튼)
  • formatting (서식에 사용되는 대부분의 도구 버튼)
  • complex (대부분의 버튼을 포함)
// buttonList import 필요
import SunEditor, {buttonList} from "suneditor-react"; 

<SunEditor setOptions={{buttonList: buttonList.basic }} />

 

커스텀 버튼

import SunEditor, {buttonList} from "suneditor-react"; 

// 사용한 버튼
// 글자 크기, 굵게, 밑줄, 기울임, 취소선, 글자색, 글자배경색, 이미지
// 다른 버튼들은 해당 라이브러리 README에서 확인 가능합니다.
<SunEditor setOptions={{buttonList: [["fontSize", "bold", 
		"underline", "italic", "strike", 
        "fontColor", "hiliteColor", "image"]] }} 
/>

 

charCounter

editor의 글자 수를 확인할 수 있다. (오른쪽 아래)

 

🔍 이벤트

사용해보았던 이벤트들만 정리했습니다. (이 외의 이벤트는 해당 라이브러리 README에서 확인 가능합니다)

 

onChange

editor 내에서 사용한 데이터를 확인할 수 있다.

import SunEditor from "suneditor-react";

const handleChange = (content) => {
  // content === SunEditor 데이터
  console.log(content):
}

<SunEditor onChange={handleChange} />

 

onImageUploadBefore

image를 editor에 업로드하기 전 (주로 image file 데이터를 상태에 저장하는 로직을 주로 사용했습니다)

import { useState } from 'react';
import SunEditor from "suneditor-react";

const [imageFile, setImageFile] = useState();

const handleImageUploadBefore = (files, info) => {
  setImageFile(files[0]);
    
  // return true를 반환해야지 함수가 종료된다.
  return true;
}

<SunEditor onImageUploadBefore={handleImageUploadBefore} />

 

onImageUpload

image를 editor에 업로드된 후 (주로 image를 삭제하는 로직을 사용했습니다)

import SunEditor from "suneditor-react";

const = handleImageUpload(targetImgElement, index, state, imageInfo) => {
  // targetImgElement : 업로드 이미지 데이터가 포함된 img 태그
  // index : 해당 이미지의 업로드 count
  // state : 이미지 업로드 상태 (create, update, delete)
  // imageInfo : 이미지 file 데이터

  if(state !== "delete") return;
  // 이미지 삭제 로직 추가
}

<SunEditor onImageUpload={handleImageUpload} />

 

getText

editor에서 작성한 텍스트의 숫자를 알 수 있다.

getText().trim()을 사용하면 텍스트가 비었는지 확인할 수 있다.

import React, { useRef } from "react";
import SunEditor from "suneditor-react";
import SunEditorCore from "suneditor/src/lib/core";
import "suneditor/dist/css/suneditor.min.css";

const Editor = () => {
  const editor = useRef<SunEditorCore>();

  const getSunEditorInstance = (sunEditor: SunEditorCore) => {
    editor.current = sunEditor;
  };
  
  editor.current?.getText() // 텍스트 내용 확인 가능
  editor.current?.getText().length // 텍스트 내용의 길이 확인 가능
  editor.current?.getText().trim().length // 텍스트 내용의 길이 확인 가능 (띄어쓰기만 한 경우 체크하려고 trim()을 사용했다)

  return <SunEditor getSunEditorInstance={getSunEditorInstance} />
};

export default Editor;

 

getImagesInfo

editor에 추가한 이미지 파일을 확인할 수 있다.

import React, { useRef } from "react";
import SunEditor from "suneditor-react";
import SunEditorCore from "suneditor/src/lib/core";
import "suneditor/dist/css/suneditor.min.css";

const Editor = () => {
  const editor = useRef<SunEditorCore>();

  const getSunEditorInstance = (sunEditor: SunEditorCore) => {
    editor.current = sunEditor;
  };
  
  editor.current?.getImagesInfo() // editor에 추가한 사진 데이터 확인 가능
  
  return <SunEditor getSunEditorInstance={getSunEditorInstance} />
};

export default Editor;

 

🔍 참고

editor 내용 빈 값 체크

getContents로 확인하려면 내용의 태그 정보까지 모두 포함되어 있다.

내가 원하는 정보는 html정보를 제외한 순수한 텍스트, 이미지에 대한 정보이므로 위의 getText, getImagesInfo를 사용해서 editor에서 빈 값을 체크하도록 했다.

const textLength = editor.current?.getText().trim().length;
const imagesLength = editor.current?.getImagesInfo().length;

const isEmptyEditor = () => {
	textLength || imagesLength ? "not empty" : "empty"
}

참고: https://github.com/JiHong88/suneditor/issues/730

 

 

궁금한 사항은 아래의 README 참고 또는 댓글로 문의 바랍니다.

잘못된 정보 또는 궁금한 내용은 댓글에 적어주세요.

감사합니다.

https://github.com/mkhstar/suneditor-react

https://github.com/JiHong88/SunEditor/blob/master/README.md#options