카테고리 없음
[React] useRef() 사용하기
BillyCho
2022. 12. 14. 01:16
DOM nodes 접근할 수 있는 속성인 ref 를 알아보자
- 함수형 컴포넌트는 useRef() 훅을 사용
- class 기반 컴포넌트는 React.createRef() 를 사용
import { useRef, useEffect } from "react"; // 1
function App() {
const inputRef = useRef(); // 2
useEffect(() => {
console.log(inputRef) // 4
console.log(inputRef.current)
inputRef.current.focus();
}, []);
return (
<div>
<input ref={domInput} type="text" /> // 3
</div>
);
}
export default App;
1. useRef 를 import 해준다
2. 변수의 선언과 함께 useRef()를 할당해준다
3. 사용하고자하는 Element의 속성 ref 에 선언한 useRef() 변수를 넣는다
4. console.log 확인

이제 원하는데로 input 에 대해서 값을 바꾸거나 함수를 실행할 수 있다
- inputRef.current.value = 123
- inputRef.current.focus()
그렇다면 컴포넌트에 (Component) 대한 ref 는 어떻게 사용할 수 있을까 ?
여기 Input.js 컴포넌트가 있다
import React, { useRef, useImperativeHandle } from "react";
const Input = React.forwardRef((props, refName) => {
return (
<input
ref={refName}
placeholder={props.placeholder || "데이터를 입력해주세요."}
type={props.type || "text"}
></input>
);
});
export default Input;
컴포넌트를 ref 참조하기 위해서는 다음의 과정이 필요하다
1. 컴포넌트는 React.forwardRef() 함수를 이용하여 만들어야한다.
forward : 전달하다, 즉 forwardRef() 는 외부에서 받은 ref 속성을 컴포넌트안의 Element에 전달한다
2. refName 에는 외부에서 전달받은 ref 이름이 들어오며 이 값을 input 의 ref에 넣어 참조시킨다
import { useRef, useEffect } from "react";
import Input from "./components/Input";
function App() {
const inputRef = useRef();
useEffect(() => {
console.log(inputRef)
console.log(inputRef.current)
// inputRef.current.value = 123
// inputRef.current.focus()
}, []);
return (
<div>
<Input ref={inputRef}></Input>
</div>
);
}
export default App;
후에 컴포넌트의 DOM 을 잘 조작할 수 있는지 확인해보면 된다
그러면 컴포넌트 Element 가 아닌 내부에 있는 함수에는 어떻게 접근할까 ?
컴포넌트 내부에 정의된 함수의 접근을 위해서는 또 다른 조치가 필요하다
import React, { useImperativeHandle } from "react";
const Input = React.forwardRef((props, refName) => {
const fireAlert = () => {
alert(123);
};
useImperativeHandle( refName, () => {
return {
alert:fireAlert
}
});
return (
<input
ref={ref}
placeholder={props.placeholder || "데이터를 입력해주세요."}
type={props.type || "text"}
></input>
);
});
export default Input;
useImperativeHandle is a React Hook lets you customize the handle exposed as a ref.
커스터 마이징을 위해서 사용한다 okay~
useImperativeHandle() 을 사용해야 한다
useImperativeHandle( refName, () => {
return {
testFunction:fireAlert
}
});
A. 외부에서 받은 ref 를 첫 번쨰 인자로 넣어준다
B. 두 번쨰 인자는 함수를 넣어주는데 return 값을 설정하여 외부에서 접근할 수 있도록 만들어준다
- testFunction 설정 시 외부에서 refName.current.testFunction 을 통해 접근할 수 있다