jskrtsth
jskrtsth

Reputation: 151

Scroll video in react

I'm building a website in ReactJS. I'm trying to incorporate a video on a webpage that I can scrub through by scrolling. Much like this example here: https://codepen.io/anon/pen/pKwQop

I am wondering how to incorporate this in my code. My first attempt to do so threw me this error here: https://i.sstatic.net/sPPhC.jpg

Here is my code so far:

import React, { Component } from 'react';
import Navbar from '../components/GlobalNav';
import Footer from '../components/GlobalFooter';
import oculus from '../../public/static/video/oculus.mp4';

import './page2.css';

class Test extends Component {
    componentDidMount() {
        var vid = document.getElementById("Oculus");
        var frameNumber = 0;
        var playbackConstant = 500;
        var setHeight = document.getElementById("Test");

        vid.addEventListener('loadedmetadata', function() {
            setHeight.style.height = Math.floor(vid.duration) * playbackConstant + "px";
        });

        function scrollPlay() {
            var frameNumber = window.pageYOffset/playbackConstant;
            vid.currentTime = frameNumber;
            window.requestAnimationFrame(scrollPlay);
        }

        window.requestAnimationFrame(scrollPlay);
    }

    render() {
        return (
            <div className="Test">
                <Navbar />
                <div className="Site-content">
                    <video
                        tabIndex="0"
                        autobuffer="autobuffer"
                        preload="preload"
                        className="Oculus"
                    >
                        <source type="video/mp4" src={oculus} />
                    </video>
                </div>
                <Footer className="Footer" />
            </div>
        )
    }
}

export default Test;

Upvotes: 0

Views: 2326

Answers (1)

samanime
samanime

Reputation: 26557

It looks like there are two issues. One, you are trying to access something by ID, but you don't seem to be declaring that idea. However, you shouldn't do that either. Instead, you should specify a ref and use that for vid.

(Note that the syntax has recently changed. That document shows the latest syntax. There is a link to the older syntax as well in there.)

class Test extends Component {
  constructor(props) {
    super(props);
    this.vid = React.createRef()
  }

  render() {
    // blah
    <video ref={this.vid} 
      /* blah */ 
    />
    // blah
  }
}

Then, instead of using vid in componentDidMount, use this.vid.current.

Another thing you can change is instead of using addEventListener, put the event callback directly on your <video> in render:

<video onLoadedMetaData={ this.metaDataCallback } />

Making these changes should more or less let it work as intended in a React-friendly way.

Upvotes: 1

Related Questions