Styled Components 와 ref

박재영·2020년 10월 22일
1

Wrapper 역할로 하고 있는 Styled Component가 아닌 그 안의 자식에 ref를 적용하고자 할 때 ref가 작동이 안된다. 이 경우 forwardRef를 사용해서 해결할 수 있다.


Forwarding Refs 공식문서

Ref forwarding 이란 컴포넌트의 자식 컴포넌트에 ref 를 전달하는 기술이다. 이 기술은 보통 어플리케이션의 대부분의 컴포넌트에 필요하지 않다. 하지만 특정 컴포넌트들, 구체적으로 말하자면 재사용가능한 컴포넌트 라이브러리들에서 가장 일반적인 시나리오로 사용된다.

// 1. FancyButton 안의 자식 컴포넌트 button에 ref를 전달하고자 함 
function FancyButton(props){
	return {
		<button className="FancyButton">
			{props.children}
		</button>
	);
}

// 2. ref는 일반적인 함수형 컴포넌트나 클래스형 컴포넌트에서 props로 받을 수 없다.
function FancyButton(props){
	return {
		<button ref={props.ref} className="FancyButton">
			{props.children}
		</button>
	);
}

const ref = React.useRef();
<FancyButton ref={ref}>Click me!</FancyButton> // Error!

// 3. React.forwardRef를 사용하면 자식 컴포넌트에 ref를 전달할 수 있다.
const FancyButton = React.forwardRef((props,ref)=> (
	<button ref={ref} className="FancyButton">
		{props.children}
	</button>
));

const ref = React.useRef();
<FancyButton ref={ref}>Click me!</FancyButton>

0개의 댓글