1

Description

I'm struggling to add the type annotation of a useRef attached on this player component: react-player to get access to the seekTo instance method as per the documentation demo source code. I can't seem to get the type to work - I'm kinda new to typescript and probably going about this wrong so any pointers would be helpful! I've looked at the react-player index.d.ts and can see the function is listed there, just need to know how I'm supposed to be writing this in.

Expected Behavior

Have access to the instance methods of the player.

Error

Property 'seekTo' does not exist on type 'MutableRefObject<ReactPlayer | null>'.ts(2339)

Steps to Reproduce

I made a small codeSandbox - basically trying to mimic the demo source for adding a ref to utilise the seekTo method onMouseUp on a range type input.

https://codesandbox.io/s/react-typescript-lqgvr?file=/src/index.tsx

Thanks!

Community
  • 1
  • 1
Kieran Osgood
  • 918
  • 6
  • 17

3 Answers3

3

I'm on a project using TS with React. I was able to get everything working by declaring:

const player = useRef<ReactPlayer>(null);

And then in my :

    <ReactPlayer ref={player} />

So any time I need to use a function like seekTo() it looks like:

player?.current?.seekTo(seconds);

No need to use:

import { BaseReactPlayerProps } from 'react-player/base';
2

A few things regarding your code:

  1. To access a ref, use ref.current instead of ref..
  2. The ref can be null, so you have to check if it is null
  3. Use currentTarget of the event to access the value instead of target.
onMouseUp={(e) => {
            if (player.current) {
              player.current.seekTo(parseFloat(e.currentTarget.value));
            }
          }}
Domino987
  • 8,475
  • 2
  • 15
  • 38
  • My god this has been annoying, and what a facepalm fix - I initially had tried player.current.seekTo knowing thats how you access refs, and when I got the null error tried the optional chaining `.?` and that understandably didn't work, so ended up removing it and somehow backtracked to the previous issue and matched it to the demo source, DUMB. Thanks mate!....the current/currentTarget always catches me out tho, thats just shameful – Kieran Osgood Apr 30 '20 at 10:03
  • 2
    Don't best yourself up. I often miss that too :) – Domino987 Apr 30 '20 at 10:22
0

I have been struggling with this too.

import { BaseReactPlayerProps } from 'react-player/base';
const MyPlayer = ({playerRef : BaseReactPlayerProps}) => {
// component code 
if (playerRef) {
  currentPlayerRef.seekTo(seconds, 'fraction');
}

}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Carlos Mori
  • 328
  • 6
  • 8