Search code examples
reactjshtml5-videowebcam

React - can't stream video from webcam


I'm trying to fix my Component to streaming data from webcam. It renders successfully and successfully gets access to webcam. But I have no idea why video tag do not plays anything. How to fix this? What am I missing?

export class WebcamStream extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            src: null
        }
        this.videoRef = React.createRef()
    }

    componentDidMount() {
        // getting access to webcam
        navigator.mediaDevices
            .getUserMedia({video: true})
            .then(stream => this.setState({src: stream}))
            .catch(console.log);
    }

    render() {
        return <video id={this.props.id}
                      ref={() => this.videoRef.srcObject = this.state.src}
                      width={this.props.width}
                      height={this.props.height}
                      autoPlay="autoplay"
                      title={this.props.title}></video>
    }
}

Solution

  • Well, I have found what was wrong. According to docs I need to use current property to make the node accessible. So, the full working example of my Webcam component:

    export class WebcamStream extends React.Component {
        constructor(props) {
            super(props);
            this.videoTag = React.createRef()
        }
    
        componentDidMount() {
            // getting access to webcam
           navigator.mediaDevices
                .getUserMedia({video: true})
                .then(stream => this.videoTag.current.srcObject = stream)
                .catch(console.log);
        }
    
        render() {
            return <video id={this.props.id}
                          ref={this.videoTag}
                          width={this.props.width}
                          height={this.props.height}
                          autoPlay
                          title={this.props.title}></video>
        }
    }
    

    this.setState was removed in prior of direct srcObject changing from promise, but I'm not sure if this React way. Maybe, more correctly is moving this.videoTag.current.srcObject = stream code as setState callback?