useRef의 사용법

CMK·2023년 2월 6일
0

useRef

목록 보기
1/1

useRef란

useRef란 리액트의 Hook중 하나로 우리가 평소 DOM을 선택할때 querySelector를 사용한것처럼
react에서는 useRef가 HTML 태그에 접근을 도와준다


useRef의 사용법

import { useRef } from "react";

export default function useRefHook()
  const fileRef = useRef(null);
  const onClickBtn = () => {
    fileRef.current.click();
    console.log(fileRef.current)
  };

return(
	<div>
  		<button onClick={onClickBtn}>등록하기</button>
    	<input type="file" ref={fileRef} style={{ display: "none" }}/>
  </div>
)

위의 코드에서 console.log를 보면

<input type="file" style="display:none">

위와같이 input태그의 정보를 가져온다

current는 DOM을 가르키고 현재 input에 ref={fileRef}을 통해 fileRef가 인풋태그의 DOM에 접근한것이다

그럼 여기서 fileRef.current.value, fileRef.current.id를 할수 있다는 것이고 현재 코드는 해당 input태그를 클릭하는 것이다


useRef 언제 사용할까???

위의 코드와 같이 input type="file" 인 input태그를 다른 태그와 연결시켜 css를 수정

웹페이지에 접속시 자동으로 입력란에 포커스가 되도록 useEffect와 함께 사용

export default function Focus() {
  const FocusOn = useRef(null);

  useEffect(() => {
    FocusOn.current.focus();
  }, []);
  return <input type="password" ref={FocusOn} />;
}

혹은

setState의 리렌더링을 방지할때 사용

export default function useRefSetState() {
  const passwordRef = useRef(null);
  const [password, setPassword] = useState("")

  
  const onClickSubmit = () => {
  	setPassword(passwordRef.current.value)
  }
  return (
  	<div>
    	<input type="password" ref={password} />;
      	<button onClick={onClickSubmit}>제출하기<button>
    </div>
  )
}

원래라면 onChange를 사용하여 값이 입력될때 마다 setState를 하여 리렌더링이 됬겠지만 위와 같이 작성하면 버튼을 누를때만 리렌더링이 된다

0개의 댓글