Trouble



부모 컴포넌트

import React, { useRef } from "react";
import WysiwygEditor from "../wysiwygEditor";

const CreatePost = () => {
  const editorRef = useRef<any>(null);

  const printRefCurrent = () => {
    console.log(editorRef.current);
  }

  return (
    <>
      <WysiwygEditor ref={editorRef} />
      <button onClick={printRefCurrent}>Click</button>
    </>
  );
};

export default CreatePost;
자식 컴포넌트

import dynamic from "next/dynamic";
import React, { useImperativeHandle, useRef, forwardRef } from "react";

import "@toast-ui/editor/dist/toastui-editor.css";

const Editor = dynamic(() => import("@toast-ui/react-editor").then((mod) => mod.Editor), { ssr: false });

const WysiwygEditor = forwardRef((props, ref) => {
  const editorRef = useRef(null);

  useImperativeHandle(ref, () => ({ current: editorRef.current }));

  return (
    <>
      <Editor
        ref={editorRef}
        height="400px"
        initialEditType="wysiwyg"
        previewStyle="vertical"
        hideModeSwitch={true}
        useCommandShortcut={true}
      />
    </>
  );
});

export default WysiwygEditor;

Click 버튼 클릭시

toast-ui라이브러리의 위지위그 에디터 컴포넌트에 ref를 전달하였지만, ref의 current가 retry라는 함수만 참조하고 있는 상황. toast-ui는 SSR환경에서는 실행될 수 없기 때문에 dynamic으로 CSR에서 동적 로드되도록 하였다. 그런데도 ref로 참조가 제대로 이루어지고 있지 않아서, ref와 dynamic 동적 로드의 타이밍이 맞지 않아 생긴 문제라고 생각되었다. useRef는 SSR환경에서는 실행되지 않기 때문에, 클라이언트에서 렌더링 시 ( 1. useRef 초기값 할당 => 2. 에디터 컴포넌트 동적로드 => 3. useRef가 생성된 에디터 컴포넌트 참조 ) 이 과정의 3번과정에서 오류가 생긴 것으로 추측했다.

 

Trouble Shooting



부모 컴포넌트

import dynamic from 'next/dynamic';
import { Editor } from '@toast-ui/react-editor';

const WysiwygEditor = dynamic(() => import('../components/WysiwygEditor'), { ssr: false });

const CreatePost = () => {
  const editorRef = useRef<Editor>(null);

  const handleButtonClick = useCallback(() => {
    if (editorRef.current) {
      const editorInstance = editorRef.current.getInstance();
      console.log('editorInstance', editorInstance);
      console.log('Editor content:', editorInstance.getMarkdown());
    }
  }, []);

  return (
	<>
    	<WysiwygEditor editorRef={editorRef} />
	    <button onClick={handleButtonClick}>Get Editor Content</button>
	</>
)}

export default CreatePost;
자식 컴포넌트

import { Editor } from '@toast-ui/react-editor';

import '@toast-ui/editor/dist/toastui-editor.css';

interface Props {
  editorRef: React.RefObject<Editor>;
}

const WysiwygEditor = ({ editorRef }: Props) => {
  return (
    <Editor
      ref={editorRef}
      initialValue="초기 내용"
      previewStyle="vertical"
      height="400px"
      initialEditType="markdown"
      useCommandShortcut
    />
  );
};

export default WysiwygEditor;

forwardRef로 ref를 가져오지 않고, 부모 컴포넌트에서 일반 prop 넘기듯이 ref를 넘기니 제대로 참조하게 되었다. 아직도 왜 이렇게 하면 제대로 참조하는지 잘 모르겠지만, 정확히 알게되면 다시 포스팅 해야겠다.

'Project > BLUE NOTE' 카테고리의 다른 글

네이밍 컨벤션 이슈  (0) 2024.08.12
BLUE NOTE 소개  (0) 2024.08.12
Hyunsoo_Kim