Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- hook
- React
- designpatterns
- Chakra
- react-hook-form
- 티스토리챌린지
- Spring
- ReactHooks
- storybook
- css
- JPA
- 오블완
- RTK
- JavaSpring
- tanstackquery
- springboot
- test
- Redux
- frontend
- golang
- typescript
- satisfiles
- Gin
- backend
- java
- javascript
- component
- go
- 웹애플리케이션서버
Archives
- Today
- Total
bkdragon's log
forwardRef 본문
React에서 useRef로 DOM 요소에 대한 참조를 얻을 수 있다. 근데 ref는 컴포넌트에는 사용할 수 없는데 그 이유는 컴포넌트는 DOM 요소를 반환하는 함수이기 때문이다. 그래서 컴포넌트에 ref를 넘기려면 forwardRef 가 필요하다.
import React, { forwardRef, Ref } from 'react';
interface MyInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
}
const MyInput = forwardRef<HTMLInputElement, MyInputProps>(
(props, ref: Ref<HTMLInputElement>) => {
return <input {...props} ref={ref} />;
}
);
MyInput.displayName = "MyInput";
export default MyInput;
forwardRef로 감싸서 컴포넌트를 만들면 된다. 이렇게 하면 부모 컴포넌트에서 input 을 직접 조작할 수 있다.
import React, { useRef } from 'react';
import MyInput from './MyInput';
function Parent() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<MyInput ref={inputRef} placeholder="Type something" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default Parent;
'React' 카테고리의 다른 글
useImperativeHandle (0) | 2024.11.27 |
---|---|
Web Speech API (1) | 2024.11.26 |
Storybook Interactions Portal Component (0) | 2024.11.17 |
Storybook Interactions (0) | 2024.11.16 |
children 을 함수해서 동적으로 스타일을 지정하기 (0) | 2024.11.14 |