728x90
useRef 를 사용하여 DOM 요소에 쉽게 접근할 수 있다.
1. 개요
마운트되었을 때부터 INPUT 창이 활성화 되어 있도록 input 태그에 focus() 메소드를 사용할 것
2. inpiut 태그를 참조할 useRef를 선언
const inputRef = useRef();
3. input 태그에 ref={} 프로퍼티로 참조시켜 준다.
<input id='input' ref={inputRef} type='text' placeholder='email을 입력해주세요'/>
4. useEffect 로 마운트부터 포커스되도록 inputRef를 가져와 focus()를 걸어준다.
*inputRef.current.focus() 는 document.getElementById('input').focus() 와 동일한 역할을 한다.
useEffect(() => {
inputRef.current.focus(); // document.getElementById('input').focus() 와 동일
},[])
5. 로그인 버튼 누른 후, 다시 포커스 시키고 input 창을 비우고 싶다면?
const login = () => {
alert(`welcome ${inputRef.current.value}`)
//여기 빈 자리에 로그인 정보 넘겨주는 로직이 들어감
console.log(inputRef.current.value)
inputRef.current.value=''; // input 비우기
inputRef.current.focus(); // 다시 포커스
}
📌 전체로 보면 이렇다.
import './App.css';
import { useRef, useEffect } from 'react';
function App() {
const inputRef = useRef();
// 마운트: 포커스한채로 시작
useEffect(() => {
inputRef.current.focus(); // document.getElementById('input').focus() 와 동일
},[])
const login = () => {
alert(`welcome ${inputRef.current.value}`)
//여기 빈 자리에 로그인 정보 넘겨주는 로직이 들어감
console.log(inputRef.current.value)
inputRef.current.value=''; // input 비우기
inputRef.current.focus(); // 다시 포커스
}
return (
<div className="App">
<input id='input' ref={inputRef} type='text' placeholder='email을 입력해주세요'/>
<button onClick={login}>로그인</button>
</div>
);
}
export default App;
728x90
'react.js' 카테고리의 다른 글
[react 리액트] Wrapper 컴포넌트만들기 (ft. props.children) (0) | 2023.06.21 |
---|---|
[reactJS] Export & Import (export default는 왜 할까?) (0) | 2023.06.20 |
[react 리액트] useRef 언제 쓰나요? (react hook) (0) | 2023.06.14 |
[react 리액트] 초간단 중복 클릭 못하게 하기 (feat. 로딩화면) (0) | 2023.06.13 |
[react 리액트] 초간단 게시판, 회원 리스트 만들기 (useState, CRUD) (0) | 2023.06.08 |