react.js

[react 리액트] useRef 사용하여 DOM 요소 접근 (feat. focus()으로 input 창에 바로 입력하게 하기)

코복이 2023. 6. 14. 14:06
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