✏️ Example -1

import React, { useEffect, useRef } from "react";

export default function UseRefsinput() {
  const inputRef = useRef();
  console.log(inputRef);

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="user name" />
    </div>
  );
}

Untitled

🚩 useRef를 통해 변수를 설정해준 후,

<input> 태그 안의 ref속성에 useRef를 통해 설정해준 변수를 연결한다.

console창에 출력해보면, 연결된 input 태그에 관련한 속성들이 출력된다.

✏️ Example -2

import React, { useEffect, useRef } from "react";

export default function UseRefsinput() {
  const inputRef = useRef();
  useEffect(() => {
    inputRef.current.focus();
  }, []);

  const login = () => {
    alert(`환영합니다. ${inputRef.current.value}님!`);
    inputRef.current.focus();
    inputRef.current.value = "";
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="user name" />
      <button onClick={login}>로그인</button>
    </div>
  );
}
  1. useEffect를 활용하여, 맨 처음 랜더링 될 때, <input>에 focus를 설정해준다.
  2. login 버튼을 클릭했을때, alert창이 켜지고, <input>에 focus와 value는 빈 string으로 만든다.