Skip to content

Instantly share code, notes, and snippets.

@craftystudio
Last active May 7, 2024 06:55
Show Gist options
  • Save craftystudio/ae145f1f1ec624e4b6be921b75b9bc63 to your computer and use it in GitHub Desktop.
Save craftystudio/ae145f1f1ec624e4b6be921b75b9bc63 to your computer and use it in GitHub Desktop.
Responsive MuxVideoPlayer, play on hover
import React, { useState, useEffect, useRef } from 'react';
import { useMuxVideo } from '@mux/react-player';
const MuxVideoPlayer = ({ videoId }) => {
const [isHovered, setIsHovered] = useState(false);
const [isPlaying, setIsPlaying] = useState(false);
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
const containerRef = useRef(null);
const { Player, playerRef, stillImageUrl, videoWidth, videoHeight } = useMuxVideo({
videoId,
autoplay: false,
loop: false,
controls: true,
muted: false,
stillImageOptions: {
time: 0, // Get the still image at the start of the video
},
});
useEffect(() => {
if (isHovered) {
setIsPlaying(true);
} else {
setIsPlaying(false);
}
}, [isHovered]);
useEffect(() => {
const handleResize = () => {
if (containerRef.current) {
setContainerSize({
width: containerRef.current.offsetWidth,
height: (containerRef.current.offsetWidth * videoHeight) / videoWidth,
});
}
};
handleResize();
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [videoWidth, videoHeight]);
return (
<div
ref={containerRef}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
style={{
position: 'relative',
width: '100%',
height: containerSize.height,
}}
>
{isPlaying ? (
<Player ref={playerRef} style={{ width: '100%', height: '100%' }} />
) : (
<img
src={stillImageUrl}
alt="Video thumbnail"
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
objectFit: 'cover',
transition: 'opacity 0.3s ease-in-out',
opacity: isHovered ? 0 : 1,
}}
/>
)}
</div>
);
};
export default MuxVideoPlayer;
@craftystudio
Copy link
Author

craftystudio commented May 7, 2024

import MuxVideoPlayer from './MuxVideoPlayer';

const MyPage = () => {
  return (
    <div>
      <MuxVideoPlayer videoId="your-mux-video-id" />
    </div>
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment