본문 바로가기

React.js

[React] forwardRef란?

반응형

https://velog.io/@hygge31/forwardRef

 

forwardRef()

부모 컴포넌트에서 생성한 ref를 자식 컴포넌트로 전달해주는 역할.리액트가 제공하는 기본 컴포넌트인 <input>은 ref 속성에 값을 설정할 수 있지만,사용자 컴포넌트의 경우 ref 속성을 forwardRef 함

velog.io

 

forwardRef란?

부모 컴포넌트에서 생성한 ref를 자식 컴포넌트로 전달해주는 역할.

리액트가 제공하는 기본 컴포넌트인 <input>은 ref 속성에 값을 설정할 수 있지만,
사용자 컴포넌트의 경우 ref 속성을 forwardRef 함수로 전달해야함.

function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): 사용자_지정_반환_타입;
T: ref 대상 컴포넌트 (Ex. input 타입은 <HTMLInputElement>)
P: InputProps
export type reactInputProps = DetailedHTMLProps<
  InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>;

export type InputProps = reactInputProps & {};

 

input 사용자 컴포넌트에서 forwardRef 사용

import type { FC, DetailedHTMLProps, InputHTMLAttributes } from 'react'
import { forwardRef } from 'react'

export type reactInputProps = DetailedHTMLProps<
  InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>

export type InputProps = reactInputProps & {}

export const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  const { className: _className, ...inputProps } = props
  const className = ['input', _className].join(' ')
  return <input ref={ref} {...inputProps} className={className} />
})

 

반응형