Skip to content

Commit 2360236

Browse files
authoredJul 6, 2021
docs(react): Added a functional React component using React.useEffect (#7203)
1 parent 14da28d commit 2360236

File tree

1 file changed

+77
-3
lines changed

1 file changed

+77
-3
lines changed
 

‎docs/guides/react.md

+77-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,87 @@
11
# Video.js and ReactJS integration
22

3-
Here's a basic ReactJS player implementation.
3+
Here are a couple ReactJS player implementations.
4+
5+
## React Functional Component and useEffect Example
6+
7+
```jsx
8+
import React from "react";
9+
import videojs from "video.js";
10+
import "video.js/dist/video-js.css";
11+
12+
export const VideoJS = ( props ) => {
13+
14+
const videoRef = React.useRef(null);
15+
const { options } = props;
16+
17+
// This seperate functional component fixes the removal of the videoelement
18+
// from the DOM when calling the dispose() method on a player
19+
const VideoHtml = ( props ) => (
20+
<div data-vjs-player>
21+
<video ref={videoRef} className="video-js vjs-big-play-centered" />
22+
</div>
23+
);
24+
25+
React.useEffect( () => {
26+
const videoElement = videoRef.current;
27+
let player;
28+
if( videoElement ) {
29+
player = videojs( videoElement, options, () => {
30+
console.log("player is ready");
31+
});
32+
}
33+
return () => {
34+
if( player ) {
35+
player.dispose();
36+
}
37+
}
38+
}, [options]);
39+
40+
return (<VideoHtml />);
41+
}
42+
export default VideoJS;
43+
44+
```
45+
46+
You can then use it like this: (see [options guide][options] for option information)
47+
```jsx
48+
import React from "react";
49+
import VideoJS from './VideoJS' // point to where the functional component is stored
50+
51+
const App = () => {
52+
53+
const videoJsOptions = { // lookup the options in the docs for more options
54+
autoplay: true,
55+
controls: true,
56+
responsive: true,
57+
fluid: true,
58+
sources: [{
59+
src: '/path/to/video.mp4',
60+
type: 'video/mp4'
61+
}]
62+
}
63+
64+
return (
65+
<>
66+
<div>Rest of app here</div>
67+
68+
<VideoJS options={videoJsOptions}/>
69+
70+
<div>Rest of app here</div>
71+
</>
72+
);
73+
}
74+
75+
```
76+
77+
## React Class Component Example
478

579
It just instantiates the Video.js player on `componentDidMount` and destroys it on `componentWillUnmount`.
680

781
```jsx
882
import React from 'react';
983
import videojs from 'video.js'
84+
import video.js/dist/video-js.css
1085

1186
export default class VideoPlayer extends React.Component {
1287
componentDidMount() {
@@ -52,10 +127,9 @@ const videoJsOptions = {
52127

53128
return <VideoPlayer { ...videoJsOptions } />
54129
```
130+
[options]: /docs/guides/options.md
55131

56-
Don't forget to include the Video.js CSS, located at `video.js/dist/video-js.css`.
57132

58-
[options]: /docs/guides/options.md
59133

60134
## Using a React Component as a Video JS Component
61135

0 commit comments

Comments
 (0)
Please sign in to comment.