skip to Main Content

I’m building a TypeScript React Native mobile app. I’m using a YouTube iframe package and I have built some custom controller elements to control it with the functions of the YouTube iframe ref object. But the ref of the object always returns undefined value. Need help

Code:

import React, { MutableRefObject, ReactNode } from "react";

import YoutubeIframe, { PLAYER_STATES, YoutubeIframeRef } from "react-native-youtube-iframe";



export default class YouTubeVideoPlayer extends React.Component<Props, State> {

  private player?: MutableRefObject<YoutubeIframeRef | null> = undefined;

  render(): ReactNode {

    return <>
      <YoutubeIframe
        videoId={this.props.id}
        ref={this.player}            // Returning undefined
        play={false}
        ...
      />
    </>;
  }
}

2

Answers


  1. declare with createRef if you use Class component

    player = React.createRef()
    

    or using useRef if you use function component

    const player  = React.useRef()
    

    you can view example

    Login or Signup to reply.
  2. Since you have a Class Component, you need to set the ref manually instead of passing it as a prop:

        return <>
          <YoutubeIframe
            videoId={this.props.id}
            ref={ref => { this.player = ref}}            
            play={false}
            ...
          />
        </>;
    

    Or what you need to do is convert the component to a function component and use useRef

    EXAMPLE

     const YouTubeVideoPlayer = ({ id }) => {
    
      // Note that whenever you need to use the ref you need to access 
      // player.current?.whatever
      const player = useRef<YoutubeIframeRef | null>(null);
    
        return (
          <>
          <YoutubeIframe
            videoId={id}
            ref={player}           
            play={false}
            ...
          />
        </>;
      )
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search