useImperativeHandle & forwardedRef 활용하기

Yuri Na·2021년 4월 16일
0

https://yrnana.dev/post/2021-04-16-useimperativehandle-forwardedref

// Child.tsx

import React, { useRef, useImperativeHandle, forwardedRef } from 'react'

interface ChildProps {}

type InputRef = { focus: () => void } | null

const Child = forwardedRef<InputRef, ChildProps>((props, ref) => {
  const inputRef = useRef<HTMLInputElement>(null)

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current?.focus()
    }
  }))

  return <input ref={inputRef} />
})
// Parent.tsx

const Parent = () => {
  const ref = useRef<InputRef>(null)

  return (
    <div>
      <Child ref={ref} />
      <button onClick={() => ref.current?.focus()}>focus</button>
    </div>
  )
}

useImperativeHandleforwardedRef를 활용하면 부모 컴포넌트가 자식 컴포넌트의 함수를 호출하거나 값을 가져올 수 있다.

profile
Frontend Developer@Kakaopay | https://yrnana.dev

0개의 댓글