React hook for accessing user media.
Using npm:
$ npm install --save react-use-user-media
Using yarn:
$ yarn add react-use-user-media
Since this module uses React Hooks, to try this out you'll need to install at least
the 16.8.0
version of react
and react-dom
:
$ yarn add react@^16.8.0 react-dom@^16.8.0
import React, { useEffect, useRef } from 'react';
import useUserMedia from 'react-use-user-media';
const constraints = { video: true };
function Example() {
const { state, stream } = useUserMedia(constraints);
const ref = useRef();
useEffect(() => {
if (state !== 'resolved' || !stream) {
return;
}
ref.current.srcObject = stream;
ref.current.play();
}, [state, stream]);
if (state === 'pending') {
return <p>Waiting...</p>;
}
if (state === 'rejected') {
return <p>Error: {error.message}</p>;
}
return <video ref={ref} />;
}
useUserMedia(Object): {
error: Error,
state: 'pending' | 'resolved' | 'rejected',
stream: MediaStream
}
Receives a constraints object
to call getUserMedia
with and returns an object with the stream,
the error and the state.
Note: When the constraints
change a new media stream will be requested,
so make sure you don't create a new constraints
object on every render.
Please feel free to submit any issues or pull requests.
MIT