[React] #8 리액트로 input 포커스 주기 : React.useRef()
input 태그를 작성하고 해당 태그에 포커스를 주고싶을 때!
html 태그에 autofocus를 명시하거나,
자바스크립트에서는 selector 함수를 통해 가져온 엘리먼트에 focus() 메소드를 통해 포커스를 줄 수 있다.
그렇다면 리액트는 ???? 🤔
우선 자바스크립트부터 확인해보자.
그냥주면 심심하니까 화면이 보여지고 3초 뒤부터 포커스를 줘보자.
우선 DOM 셀렉터로 input을 가져오고,
setTimeout()으로 3초 뒤에 focus()를 주도록 작성할 것이다.
const autoFocusInput = document.getElementById("input");
setTimeout(() => {
autoFocusInput.focus();
}, 3000);
이제 리액트로 바꿔보자.
이전과 동일하게 CDN unpkg 코드를 넣어서 html 내부에서 작성할 것이다!
root 내부에 렌더될 <App/>을 먼저 작성해보자.
const root = docuemnt.getElementById("root");
const App = () => {
return (
<>
</>
);
};
ReactDOM.render(<App/>, root);
우리는 Input이 필요하니 하나 넣어주자.
const root = docuemnt.getElementById("root");
const App = () => {
return (
<>
<input/>
</>
);
};
ReactDOM.render(<App/>, root);
여기까지는 쉽지만
이제 ,,, 어떻게 input을 찾아서 focus를 줄 것인가!!
이때 사용할 수 있는 것이 바로 useRef() 훅이다.
useRef()
리액트에서
- 특정 엘리먼트의 위치나 크기를 가져와야 할 때
- 스크롤바 위치를 가져오거나 설정해야 할 때
- 포커스를 설정해할 때
등등에 사용할 수 있다.
+)
우리는 지금 함수형 컴포넌트의 형태를 사용하고 있다.
이때는 useRef()를 사용하고,
클래스형 컴포넌트에서는 React.createRef()를 사용!
useRef 사용법 !
- Ref 객체를 먼저 만들어줘야한다.
- 그리고 선택하고 싶은 DOM에 props로 ref={ /*생성된 Ref 객체 이름*/ }를 설정해준다.
const inputRef = React.useRef();
자바스크립트에서처럼 가져온 엘리먼트에 inputRef.focus();를 주면 될까? 안된다.
inputRef.current 까지 작성해야 우리가 원하는 DOM에 접근할 수 있다.
(Ref 객체의 current 값 == Ref.current => Ref의 DOM을 가르킴!)
아래와 같이 작성해주면 완성!
const root = document.getElementById("root");
const App = () => {
const inputRef = React.useRef();
//미리 말하지만 여기서 이건 안된다. 난,, 모른다 ,, 🥲
//inputRef.current.focus();
React.useEffect(() => {
setTimeout(() => {
inputRef.current.focus();
}, 3000);
}, []);
return (
<>
<input ref={inputRef} />
</>
);
};
ReactDOM.render(<App />, root);
왜 useEffect()를 사용해야하는지 이해가 안가서 슬퍼서
추가로 만들어 본 버튼을 클릭하면 input에 focus를 주는 모양!
const root = document.getElementById("root");
const App = () => {
const inputRef = React.useRef(
function focusInput() {
inputRef.current.focus();
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Click</button>
</>
);
};
ReactDOM.render(<App />, root);
Ref와 DOM – React
A JavaScript library for building user interfaces
ko.reactjs.org
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
⚠️ 아래 내용은 모두 개인적인 참고 / 기록을 위한 용도입니다. 참고해주시고 편안하게 봐주세요 :) ⚠️
*** 혹시라도 잘못된 정보가 있다면 언제든지 알려주시면 감사하겠습니다 ! ***