[React Docs Beta] 1-2. forwardRef (2)

2023. 3. 7.·🎨 프론트엔드 공부/React & Next

React Docs (beta) 번역 및 정리

더보기

Built-in React APIs

1. createContext

2. forwardRef

 

📍비디오 재생 및 중지하기 예제

- 예제

https://beta.reactjs.org/reference/react/forwardRef#examples

 

forwardRef

A JavaScript library for building user interfaces

beta.reactjs.org

 

video element는 자체 메서드로 play() 와 pause() 를 갖는다

App 컴포넌트와 video element가 있는 MyVideoPlayer 컴포넌트가 있다고 가정할 때, 

App 컴포넌트에서 직접 video element에 접근하게 해보자

 

✅MyVideoPlayer.js

import { forwardRef } from 'react';

const VideoPlayer = forwardRef(function VideoPlayer({ src, type, width }, ref) {
  return (
    <video width={width} ref={ref}>
      <source
        src={src}
        type={type}
      />
    </video>
  );
});

export default VideoPlayer;

 

video element (DOM 노드) 에 ref를 지정한다

 

✅App.js

import { useRef } from 'react';
import MyVideoPlayer from './MyVideoPlayer.js';

export default function App() {
  const ref = useRef(null);
  return (
    <>
      <button onClick={() => ref.current.play()}>
        Play
      </button>
      <button onClick={() => ref.current.pause()}>
        Pause
      </button>
      <br />
      <MyVideoPlayer
        ref={ref}
        src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
        type="video/mp4"
        width="250"
      />
    </>
  );
}

 

- forwardRef로 만든 컴포넌트에 ref를 전달해줘야 한다

- useRef 로 만든 ref 객체를 여기서 조작할 수 있다

 

📍여러 컴포넌트 단계를 통해 ref 전달하기

예를 들어 App > FormField > MyInput 컴포넌트 3단계로 ref를 전달할 수 있다

- ref를 props로 받으려면, forwardRef로 만든 컴포넌트이어야 하므로,

FormField와 MyInput 컴포넌트 양쪽에서 forwardRef를 각각 사용하면 된다

 

📍useImperativeHandle 훅으로 forwardRef로 만든 컴포넌트에서 ref DOM 노드 제어하기

useImperativeHandle 훅을 사용하면 ref.current 이하의 메서드를 forwardRef 컴포넌트 레벨에서 정의할 수 있다

 

✅MyInput.js

import { forwardRef, useRef, useImperativeHandle } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => {
    return {
      focus() {
        inputRef.current.focus();
      },
      scrollIntoView() {
        inputRef.current.scrollIntoView();
      },
    };
  }, []);

  return <input {...props} ref={inputRef} />;
});

export default MyInput;

 

✅App.js

import { useRef } from 'react';
import MyInput from './MyInput.js';

export default function Form() {
  const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <MyInput label="Enter your name:" ref={ref} />
      <button type="button" onClick={handleClick}>
        Edit
      </button>
    </form>
  );
}

 

📍ref 관련 주의사항

- ref를 과용하면 안된다

- props로 표현할 수 없는 명령형 동작에만 refs를 사용해야 한다.

예) 특정 노드로 스크롤 또는 포커스, 애니메이션 트리거, 텍스트 선택 등

 

'🎨 프론트엔드 공부/React & Next' 카테고리의 다른 글
  • [React Docs Beta] 1-5. startTransition
  • [React Docs Beta] 1-4. memo
  • [React Docs Beta] 1-2. forwardRef (1)
  • [React Docs Beta] 1-1. createContext
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (516)
      • 🎨 프론트엔드 공부 (253)
        • JS & TS (92)
        • HTML & CSS (22)
        • React & Next (49)
        • Vue & Nuxt (22)
        • 기타 (68)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (6)
        • Work (0)
        • Toy (6)
      • ⚙️ 개발 팁 & 노하우 (21)
        • 프론트엔드 (6)
        • 기타 (15)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
[React Docs Beta] 1-2. forwardRef (2)
상단으로

티스토리툴바