6

I am trying to get a webcam feed to display on my app using react hooks. I also need to be able to capture the latest image from the feed

I believe I have the foundations but am missing something.

import React,{useState,useEffect} from "react"


export function VideoFeed(){
const[constraints] = useState({width:300,height:300})

useEffect(()=>{
    navigator.mediaDevices.getUserMedia({video:true})
    .then(stream=>{
        let video = document.querySelector('video')
        video.source = stream;
        video.play();
    })
    .catch(e=>{
        console.log(e)
    })
})

return(
    <video autoPlay ={true} id ="video"></video>
)
}
GrepThis
  • 642
  • 1
  • 11
  • 22

2 Answers2

14

See How to access a DOM element in React? instead of document.querySelector.

When applied with useRef hook and fixing how often useEffect needs to execute, it would look something like this:

export function VideoFeed() {
  const videoEl = useRef(null)

  useEffect(() => {
    if (!videoEl) {
      return
    }
    navigator.mediaDevices.getUserMedia({video:true})
      .then(stream => {
        let video = videoEl.current
        video.srcObject = stream
        video.play()
      })
  }, [videoEl])

  return <video ref={videoEl} />
}
Aprillion
  • 21,510
  • 5
  • 55
  • 89
  • Its throwing error "Object is possibly 'null'. TS2531" at line "video.srcObject = stream". Its showing cavet (^) at "video" – Satyam Jun 19 '20 at 16:08
  • this is javascript code, not typescript. videoEl.current will not be null inside useEffect for an unconditional ref... the dependency check was just to make eslint happy, so if TS needs more convincing before it is happy too, you should know what to do (if you don't, you shouldn't be using TS probably.. but use an if !video.current inside .then) – Aprillion Jun 19 '20 at 17:03
-2

Found the issue.

Change

 video.source = stream;

To:

 video.srcObject = stream;

Viola

GrepThis
  • 642
  • 1
  • 11
  • 22
  • 1
    no no no, `document.querySelector('video')` => [useRef](https://reactjs.org/docs/hooks-reference.html#useref) – Aprillion Apr 13 '19 at 09:47