'Create ref to external class component inside functional component in React

I would like to use react player library in my app

import React, { useEffect, useRef } from "react";
import ReactPlayer from "react-player";
import { useSelector } from "../../../redux/useSelector";

const VIDEO_URL =
  "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";

export const Player: React.FC = React.memo(() => {
  const player = React.useRef<any>(null);

  const targetTimestamp = useSelector((state) => {
    const {
      timestamps: { selectedTimestamp },
    } = state;
    return (selectedTimestamp && selectedTimestamp.timestamp) || 0;
  });

  useEffect(() => {
    console.log(player.current);
    player.current && player.current.seekTo(targetTimestamp );
  }, [targetTimestamp]);

  return (
    <ReactPlayer
      ref={player}
      url={VIDEO_URL}
      controls
      width={1280}
      height={720}
    />
  );
});

console.log(player.current); works, but on the next line I get the error

Uncaught TypeError: Cannot read property 'seekTo' of undefined

enter image description here

What's wrong? I can't use useRef here? Should I make Player class component? How to fix it and make it work?



Solution 1:[1]

    //// 
    let player;
      const ref = (playerRef) => {
        player = playerRef;
      }
    
    ////
     const seekHandler = (event) => {
   ....
    player.seekTo(parseFloat(event.target.value), "fraction");
...
  };
    
    ...
     <ReactPlayer
              ref={ref}
    .....

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serdar Sar?ta?