이챙의 개발 log
useRef props 전달할때 null 값 문제를 forwardRef를 사용하여 해결하기
﹒2021. 8. 12.
useRef는 react에서 DOM연결을 해주는 HOOK입니다.
DOM연결을 원하는 element에 ref 속성을 넣어주면 useRef가 객체를 반환하여 current속성에 dom을 넣어주죠
import React, { useRef } from "react";
const App = () => {
const userNameRef = useRef(null);
return (
<div>
<input type="text" ref={userNameRef} />
</div>
);
};
export default App;
오호.. 아주 쓸모있는 함수입니다
그런데 부모컴포넌트에서 자식 컴포넌트에게 ref를 사용하고 싶다면?
//App.js
import React, { useRef } from "react";
import Input from "./Input";
const App = () => {
const userNameRef = useRef(null);
return (
<div>
<Input ref={userNameRef} />
</div>
);
};
export default App;
//Input.js
import React from "react";
const Input = ({ref}) => {
return <input ref={ref} />;
};
export default Input;
그럼 ref로 props를 넘기면 어떨까 라는 생각이 들어 위와 같은 시도를 하게됩니다.
하지만 이경우에 콘솔창을 찍어보면 current속성에 null 값이 나옵니다
브라우저가 왜 null 이 나오는지 친절하게 오류를 알려주죠.
컴포넌트에서 ref를 제공할 수 없다! ref 접근 못하겠어! React.forwardRef() 를 사용해봤니?
부모 컴포넌트에서 자식컴포넌트에게 ref를 전달할수 없다는 것인데요.
그럼 브라우저가 알려준대로 forwardRef()를 사용해 봅시다!
//App.js
import React, { useRef } from "react";
import Input from "./Input";
const App = () => {
const userNameRef = useRef(null);
return (
<div>
<Input type="number" ref={userNameRef} />
</div>
);
};
export default App;
//Input.js
import React, { forwardRef } from "react";
const Input = (props, ref) => {
return <input {...props} ref={ref} />;
};
export default forwardRef(Input);
component에 forwardRef를 사용하게되면
props는 첫번째로 받고 두번째에 ref 를 받을 수 있습니다.
부모 컴포넌트에서 useRef를 자식 컴포넌트에게 props로 ref를 전달하여 사용을 할 수 있게 되죠!
콘솔창에서 확인해보면 current에 element가 들어와 있는걸 확인하실 수 있습니다
'react' 카테고리의 다른 글
useTransition으로 성능 개선하기 (0) | 2024.02.28 |
---|---|
react+webpack+tailwindcss 설치하기! (0) | 2022.09.19 |
React hooks를 class components 대신 사용 해야 하는 이유는 뭘까? (0) | 2021.08.27 |
[styled components] class를 추가해서 style을 변경하고 싶을때 props 이용하기(addClass) (0) | 2021.05.31 |
React useEffect 이해해서 사용하기 (0) | 2021.05.19 |
이챙(leechaeng)
프론트엔드 개발도 하고 뛰기도 하고