Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get webcam feed with react hooks?

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>
)
}
like image 850
GrepThis Avatar asked Apr 12 '19 16:04

GrepThis


People also ask

How do I use getUserMedia in React?

Try this? import React, { useEffect } from 'react'; const Chat = (props) => { useEffect(() => { var constraints = { video: true, audio: true }; async function getMedia(constraints) { let stream = null; try { stream = await navigator. mediaDevices. getUserMedia(constraints); // console.

Is useMemo React hook?

React has a built-in hook called useMemo that allows you to memoize expensive functions so that you can avoid calling them on every render. You simple pass in a function and an array of inputs and useMemo will only recompute the memoized value when one of the inputs has changed.

Are React Hooks still used?

React hooks have been around for some time now, yet many React developers are not actively using them. I see two primary reasons behind this. The first reason is that many React developers are already involved in a large project, which requires a significant effort to migrate the entire codebase.


Video Answer


1 Answers

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} />
}
like image 156
Aprillion Avatar answered Oct 20 '22 15:10

Aprillion