Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams class VideoPlayer extends PureComponent { componentDidMount() { const { videoSrc } = this.props; const { playerRef } = this.refs; this.player = videojs(playerRef, { autoplay: true, muted: true }, () => { this.player.src(videoSrc); componentWillUnmount() { if (this.player) this.player.dispose() render() { return ( <div data-vjs-player> <video ref="playerRef" className="video-js vjs-16-9" playsInline />

After adding React Hooks

import React, { useEffect, useRef } from 'react';
import videojs from 'video.js';
function VideoPlayer(props) {
  const { videoSrc } = props;
  const playerRef = useRef();
  useEffect(() => {
    const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
      player.src(videoSrc);
    return () => {
      player.dispose();
  return (
    <div data-vjs-player>
      <video ref="playerRef" className="video-js vjs-16-9" playsInline />

I got the error

Invariant Violation: Function components cannot have refs. Did you mean to use React.forwardRef()?

But I am using React Hooks useRef instead of refs actually. Any guide will be helpful.

You are passing a string to the video element's ref prop. Give it the playerRef variable instead.

You can also give useEffect an empty array as second argument as you only want to run the effect after the initial render.

function VideoPlayer(props) {
  const { videoSrc } = props;
  const playerRef = useRef();
  useEffect(() => {
    const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
      player.src(videoSrc);
    return () => {
      player.dispose();
  }, []);
  return (
    <div data-vjs-player>
      <video ref={playerRef} className="video-js vjs-16-9" playsInline />
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.