2

Based on the React documentation that I looked at, I think I would use "useRef" to update a function, but I'm not sure. I want to fire an event to mute a video there is a scroll event. Right now I'm using onClick to play/pause the video.

Video.js

import React, { useRef, useState } from "react";
import "./Video.css";

function Video({ url }) {
  const [muted, setMuted] = useState(true);
  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);

  var Chrome =
    navigator.userAgent.includes("Chrome") &&
    navigator.vendor.includes("Google Inc");

  const onVideoPress = () => {
    if (playing && !Chrome) {
      videoRef.current.pause();
      setPlaying(false);
      setMuted(true);
    } else if (playing && Chrome) {
      videoRef.current.pause();
      setPlaying(false);
      setMuted(false);
    } else {
      videoRef.current.play();
      setPlaying(true);
      setMuted(false);
    }
  };

  return (
    <div className="video">
      <video
        className="video__player"
        autoPlay={true}
        loop={true}
        muted={muted}
        playsInline={true}
        // controls
        ref={videoRef}
        onClick={onVideoPress}
      >
        <source className="video__controls" src={url} type="video/mp4"></source>
      </video>
      {/* <VideoFooter /> */}
    </div>
  );
}

export default Video;

This is not the same How to add scroll event in react component because I am not extending the function as a component.

  • Does this answer your question? [How to add scroll event in react component](https://stackoverflow.com/questions/39325581/how-to-add-scroll-event-in-react-component) – lifeisfoo Dec 01 '20 at 17:53

2 Answers2

1

I used onScroll={()=> someFunc()}

0

Using scroll event listener you should be able to achieve what you are seeking.

  • inside useEffect define an event scroll listener

    document.addEventListener('scroll', function(e) {
    
           // your logic goes here
          });
    
keshav
  • 135
  • 4
  • would I use onScroll in my video element and call the function there? –  Dec 01 '20 at 20:25
  • I tried this: `useEffect(() => { document.addEventListener("scroll", function (e) { e.setMuted(true) }); });` is that what you meant? –  Dec 01 '20 at 20:29
  • when I add ``useEffect(() => { document.addEventListener("scroll", function (e) { e.alert("hi"); }); }); `` nothing happens –  Dec 01 '20 at 20:52
  • don't use e.alert. Just try alert("hi"). It should work. Also don't do e.setMuted(true), e is the event object. Try using setMuted(true) Directly. – keshav Dec 02 '20 at 03:53