게시글 수정 페이지에서 reactQuill에 게시글 수정 전에 입력한 값을 받아오려고 했다.
기존 코드
import dynamic from "next/dynamic"
import "react-quill/dist/quill.snow.css"
const ReactQuill = dynamic(async () => await import("react-quill"), {
ssr: false,
})
export default function BoardWriteUI(props: IBoardWriteUIProps) {
const QuillRef = useRef<ReactQuill>()
let quill = QuillRef.current?.getEditor()
<ReactQuill
placeholder={
props.isEdit
? props.data?.fetchUseditem.contents
: "상품을 설명해주세요"
}
onChange={props.handleChangeContents}
style={{ width: "100%", height: "300px" }}
ref={QuillRef}
/>
}
reactquill ref.getEditor is not a function 에러가 떴다.
개선
const ReactQuill = dynamic(
async () => {
const { default: RQ } = await import("react-quill")
return ({ forwardedRef, ...props }) => <RQ ref={forwardedRef} {...props} />
},
{
ssr: false,
}
)
const QuillRef = useRef<ReactQuill>(false)
useEffect(() => {
if (props.isEdit) {
if (QuillRef.current) {
const quill = QuillRef.current.getEditor()
quill?.clipboard.dangerouslyPasteHTML(0, "test")
}
}
}, [QuillRef])
export default function BoardWriteUI(props: IBoardWriteUIProps) {
const QuillRef = useRef<ReactQuill>()
let quill = QuillRef.current?.getEditor()
<ReactQuill
placeholder={
props.isEdit
? props.data?.fetchUseditem.contents
: "상품을 설명해주세요"
}
onChange={props.handleChangeContents}
style={{ width: "100%", height: "300px" }}
forwardedRef={QuillRef}
/>
1. const ReactQuill = dynamic(...)
Next.js에서 제공하는 'dynamic' 함수를 사용하여 클라이언트-사이드에서만 'react-quill' 모듈을 불러온다.
2. const QuillRef = useRef<ReactQuill>(false)
useRef를 사용해 'ReactQuill' 타입의 'QuillRef'를 정의하며, false 값을 초기값으로 설정한다.
3. useEffect(...)
'useEffect' 훅을 사용하여, 조건문에 따른 작업을 실행한다.
여기서 props.isEdit이 참일 때, QuillRef가 존재한다면 'getEditor()' 메서드를 호출해 Quill 인스턴스를 가져오고, 'dangerouslyPasteHTML' 메서드를 사용해 편집기의 커서 위치에 HTML을 삽입한다.
4. const QuillRef = useRef<ReactQuill>()
'ReactQuill' 타입의 'QuillRef'를 정의한다.
5. let quill = QuillRef.current?.getEditor()
'current' 속성에서 Quill 인스턴스를 가져온다.
6. <ReactQuill ... />
'ReactQuill' 컴포넌트를 렌더링하고, 여러 속성을 전달한다.
forwardedRef를 사용하는 이유?
Next.js의 dynamic 함수를 사용하여 불러온 'react-quill' 모듈에서 ReactQuill 컴포넌트에 직접 참조(ref)를 전달하기 위해서다.
리액트에서 ref 전달이 일반적으로 ref라는 속성을 사용해 이루어지지만, 여기서 `forwardedRef`를 사용하는 것은 `dynamic 함수와의 호환성` 때문이다. dynamic 함수를 통해 생성된 컴포넌트는 기본적으로 ref 속성을 자동으로 전달하지 않는다. 따라서 원하는 컴포넌트에 ref를 전달하기 위해서는 그것을 명시적으로 수동으로 전달해야 한다. 이를 통해 ReactQuill 컴포넌트의 참조를 얻게 된다.
결과적으로, 이 방법은 Next.js의 dynamic 함수를 사용하면서도 필요한 외부 컴포넌트에 대한 참조를 유지하고 접근할 수 있게 해준다.
참고 자료
https://shinejaram.tistory.com/71
React-Quill을 활용하여 게시판 만들기(with TypeScript)
이번 포스팅은 위지윅(WYSIWIG) 게시판 중의 하나인 React-Quill을 활용한 게시판 만드는 방법 입니다. Quill quill은 rich text editor의 일종으로 마이크로소프트 등의 기업에서 후원하고 있는 텍스트 에디
shinejaram.tistory.com
How to access ReactQuill Ref when using dynamic import in NextJS?
I'm running into a funny problem. I'm using NextJS for its server-side rendering capabilities and am using ReactQuill as my rich-text editor. To get around ReactQuill's tie to the DOM, I'm dynamica...
stackoverflow.com
'TIL' 카테고리의 다른 글
브라우저의 기본 구조와 렌더링 과정 (0) | 2023.09.26 |
---|---|
제품 이미지 주소가 담긴 배열 요소 받아오기 (0) | 2023.08.16 |
최근 본 상품 구현 (0) | 2023.08.11 |
refreshToken (0) | 2023.08.03 |
이벤트루프 (0) | 2023.08.03 |