실전 단아 개발 가이드

React ref 사용, DOM 접근 방법

#단아 2024. 1. 18. 09:52
반응형

useRef Hook함수 사용

useRef는 current라는 속성을 가진 ref 객체를 반환한다.

 

current의 초깃값은 useRef에 파라미터로 넘긴 값을 초깃값으로 가지고 있다.

null로 초기화한다. 

import { useRef } from "react";

function App() {
  const inputRef = useRef(null);
  const onFocus = () => {
    inputRef.current.focus();
  };
  return (
    <div className="App">
      <input type="text" ref={inputRef} />
      <button onClick={onFocus}>focus the input</button>
    </div>
  );
}

export default App;

 

 

 

반응형