Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created November 11, 2021 20:40
Show Gist options
  • Save lejonmanen/f44e5047c146e2dc88a320ac1dd120f3 to your computer and use it in GitHub Desktop.
Save lejonmanen/f44e5047c146e2dc88a320ac1dd120f3 to your computer and use it in GitHub Desktop.
Use MediaDevices to display video stream from webcam in a React component.
import { useRef } from 'react'
const MediaDevice = () => {
const videoRef = useRef(null)
const handleVideoOn = () => assignStream(videoRef.current)
const handleVideoOff = () => videoRef.current.srcObject = null
return (
<div>
<p>
<button onClick={handleVideoOn}> Turn video on </button>
<button onClick={handleVideoOff}> Turn video off </button>
</p>
<video ref={videoRef}> </video>
</div>
)
}
async function assignStream(videoElement, constraints = { video: true }) {
const stream = await navigator.mediaDevices.getUserMedia(constraints)
videoElement.srcObject = stream
videoElement.addEventListener('loadedmetadata', () => {
videoElement.play()
})
}
export default MediaDevice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment