개발자
등록 버튼을 눌렀을 때, 입력 한 값을 가져오고 싶은데, undefined가 뜹니다. 어떻게 가져올 수 있는걸까요? ㅜㅜ
1import * as Write from "./BoardWrite.styles";
2import dynamic from "next/dynamic";
3import "@toast-ui/editor/dist/toastui-editor.css";
4import { EditorProps } from "@toast-ui/react-editor";
5import { CommentInput } from "../../../VisitLog/VisitLog.styles";
6import { useEffect, useRef, useState } from "react";
7
8const Editor = dynamic<EditorProps>(
9 () => import("@toast-ui/react-editor").then((m) => m.Editor),
10 { ssr: false }
11);
12
13export default function BoardWrite() {
14 const contentRef = useRef(null);
15
16 const onChangeContent = () => {
17 const data = contentRef.current?.getInstance().getHTML();
18 console.log(data);
19 };
20
21 const [title, setTitle] = useState("");
22 const [content, setContent] = useState("");
23 // url hash
24 let hash;
25
26 useEffect(() => {
27 // get url hash
28 // ex) #blog => blog
29 hash = window.location.hash.split("#")[1];
30 console.log(hash);
31 }, []);
32
33 const onSubmit = () => {
34 console.log(contentRef.current?.getInstance().getHTML());
35 console.log(contentRef.current?.getInstance().getMarkdown());
36 };
37
38 return (
39 <Write.Wrapper>
40 <CommentInput
41 style={{ width: "100%", marginBottom: "20px" }}
42 placeholder="title"
43 onChange={(e) => {
44 setTitle(e.target.value);
45 console.log(title);
46 }}
47 />
48 <Editor
49 ref={contentRef}
50 onChange={onChangeContent}
51 initialValue="type here!"
52 previewStyle="vertical"
53 height="100%"
54 initialEditType="markdown"
55 useCommandShortcut={false}
56 hideModeSwitch={true}
57 />
58 <button onClick={onSubmit}>등록</button>
59 </Write.Wrapper>
60 );
61}
답변 1
안녕하세요! dynamic import를 하는 컴포넌트는 forwardRef로 ref를 넘겨주셔야 합니다. 참고해보시면 좋을 것 같아요 :) - https://codesandbox.io/p/sandbox/bold-dream-uwh8dp?file=%2Fpages%2Findex.tsx - https://velog.io/@broccoliindb/Next.js-Editor-SSR-REF-%EC%9D%B4%EC%8A%88
준영
작성자
프론트엔드 개발자 • 2023년 03월 02일
우선 답변감사드립니다! toast editor를 컴포넌트를 따로 빼서, 컴포넌트 자체를 dynamic import하는 방법으로 해결했습니다. 정확한 이유는 모르지만.. 그렇게 해보니 forwardRef를 사용하지 않아도 ref를 넘길 수 있게 되었습니다!
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!