video.js のインストール
npm i video.js
npm i -D @types/video.js
src/VideoPlayer.tsx
import React, { useEffect, useRef, useState } from 'react';
import videojs from 'video.js';
import Player from 'video.js/dist/types/player';
interface VideoPlayerProps {
src: string;
type?: string;
}
const VideoPlayer: React.FC<VideoPlayerProps> = ({
src,
type = 'video/mp4',
}) => {
const videoRef = useRef<HTMLVideoElement | null>(null);
const playerRef = useRef<Player | null>(null);
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
return () => setIsMounted(false);
}, []);
useEffect(() => {
if (isMounted && videoRef.current && !playerRef.current) {
const videoElement = videoRef.current;
const player = videojs(
videoElement,
{
controls: true,
fluid: true,
sources: [
{
src: src,
type: type,
},
],
},
() => {
console.log('Player is ready');
}
);
playerRef.current = player;
return () => {
if (playerRef.current) {
playerRef.current.dispose();
playerRef.current = null;
}
};
}
}, [isMounted, src, type]);
useEffect(() => {
if (isMounted && playerRef.current) {
playerRef.current.src({ type: type, src: src });
}
}, [isMounted, src, type]);
return (
<div data-vjs-player>
<video ref={videoRef} className="video-js" />
</div>
);
};
export default VideoPlayer;
src/App.tsx
import './App.css';
import VideoPlayer from './VideoPlayer';
function App() {
return <VideoPlayer src="https://vjs.zencdn.net/v/oceans.mp4" />;
}
export default App;
npm i amazon-ivs-player copy-webpack-plugin