[React Hook] useRef

young·2022년 6월 30일
0

6/23~7/20 Section 3 TIL

목록 보기
8/21

useRef

JavaScript에서 DOM Selector 함수를 사용하듯 React에서도 특정 DOM을 선택해야 하는 상황이 발생한다.

아래와 같이 DOM 엘리먼트의 주소값을 활용해야 할 때 useRef로 DOM 노드, 엘리먼트, React 컴포넌트 주소값을 참조할 수 있다.

  • focus
  • text selection
  • media playback
  • 애니메이션 적용
  • d3.js, greensock 등 DOM 기반 라이브러리 활용

useRef 사용법

import { useRef } from 'react'; //useRef 호출

const App = () => {
  const inputEl = useRef(null); //`useRef()`를 사용하여 Ref 객체를 만든다.

  const onChange = () => {
    ...
    inputEl.current // Ref 객체의 .current값은 DOM을 가리킨다.
    ...
  }
    
  /* 생략 */

  return (
    ...
    <input ref={inputEl} onChange={onChange} /> //선택하고 싶은 DOM에 ref값으로 설정한다.
    ...
  )
};

useRef를 통해 만든 ref 객체에는 DOM 엘리먼트의 주소가 담긴다.
이 주소값은 컴포넌트가 리렌더링 되더라도 바뀌지 않는다.


useRef 예제


input: focus

import React, { useRef } from "react";

const Focus = () => {
  const firstRef = useRef(null);
  const secondRef = useRef(null);
  const thirdRef = useRef(null);

  const handleInput = (event) => {
    
    //엔터를 눌렀을 때
    if (event.key === "Enter") { 
      
      //event.target === <input></input>
      //firstRef.current === <input></input>
      if (event.target === firstRef.current) {
        secondRef.current.focus();
        event.target.value = "";
      }
      
      else if (event.target === secondRef.current) {
        thirdRef.current.focus();
        event.target.value = "";
      }
      
      else if (event.target === thirdRef.current) {
        firstRef.current.focus();
        event.target.value = "";
      }
      
      else {
        return;
      }
    }
  };

  return (
    <div>
      <h1>타자연습</h1>
      <h3>각 단어를 바르게 입력하고 엔터를 누르세요.</h3>
      <div>
        <label>hello </label>
        <input ref={firstRef} onKeyUp={handleInput} />
      </div>
      <div>
        <label>world </label>
        <input ref={secondRef} onKeyUp={handleInput} />
      </div>
      <div>
        <label>codestates </label>
        <input ref={thirdRef} onKeyUp={handleInput} />
      </div>
    </div>
  );
};

export default Focus;

media playback

import { useRef } from "react";

export default function App() {
  const videoRef = useRef(null);

  const playVideo = () => {
    
    //videoRef.current === <video ...>...</video>
    videoRef.current.play();
  };

  const pauseVideo = () => {
    videoRef.current.pause();
    videoRef.current.remove();
  };

  return (
    <div className="App">
      <div>
        <button onClick={playVideo}>Play</button>
        <button onClick={pauseVideo}>Pause</button>
      </div>
      
      //선택하고 싶은 엘리먼트에 ref를 지정해준다.
      <video ref={videoRef} width="320" height="240" controls>
        <source
          type="video/mp4"
          src="비디오링크"
        />
      </video>
    </div>
  );
}
profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글