useContentEditable

contentEditable을 사용할 때 React에서 상태 관리를 위해 사용합니다.

Copy Code

hooks/use-content-editable.tsx
'use client'
 
import { useEffect, useRef, useState } from 'react'
import type { ChangeEvent } from 'react'
 
function useContentEditable(initialValue: string = '') {
  const ref = useRef<HTMLDivElement>(null)
  const [value, setValue] = useState<string>(initialValue)
 
  const onInput = (e: ChangeEvent<HTMLDivElement>) =>
    setValue(e.target.innerText)
 
  const setContent = (content: string) => {
    if (!ref.current) return
    ref.current.innerText = content
    setValue(content)
  }
 
  useEffect(() => {
    if (initialValue) setContent(initialValue)
  }, [initialValue])
 
  return { content: value, setContent, onInput, ref }
}
 
export default useContentEditable

Usage

const Page = () => {
  const { content, setContent, onInput, ref } =
    useContentEditable('[initial Value]')
 
  return <div contentEditable onInput={onInput} ref={ref}></div>
}

References