Skip to content

Instantly share code, notes, and snippets.

@solilokiam
Created October 22, 2019 14:22
Show Gist options
  • Save solilokiam/5125b505c1c40e3a644860cc8af927b5 to your computer and use it in GitHub Desktop.
Save solilokiam/5125b505c1c40e3a644860cc8af927b5 to your computer and use it in GitHub Desktop.
import React, { useRef, useState } from 'react';
import styled from 'styled-components';
import { PlayCircle } from 'styled-icons/feather/PlayCircle';
import useOnScreen from '../hooks/onScreen';
import { SkeletonImage } from './styles/skeleton';
const ThumbWrapper = styled.div`
img {
position: absolute;
top: 0;
left: 0;
width: 100%;
${props => (props.active ? 'display: none;' : '')}
}
video {
width: 100%;
}
`;
const VideoPlayOverlay = styled.div`
opacity: 0;
svg {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 50px;
width: 50px;
color: #f5234a;
}
${ThumbWrapper}:hover & {
background: rgba(0, 0, 0, 0.1);
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 1;
position: absolute;
text-align: center;
transition-duration: 0.5s;
width: 100%;
height: 100%;
}
`;
const VideoThumb = ({ thumbUrl, title, src }) => {
const playerRef = useRef();
const itemRef = useRef();
const onScreen = useOnScreen(itemRef);
const [active, setActive] = useState(false);
const play = () => {
setActive(true);
playerRef.current.play();
};
const stop = () => {
setActive(false);
playerRef.current.pause();
};
return (
<div ref={itemRef}>
{onScreen ? (
<ThumbWrapper active={active} onMouseEnter={play} onMouseLeave={stop}>
<img src={thumbUrl} alt={title} />
<VideoPlayOverlay>
<PlayCircle />
</VideoPlayOverlay>
<video
ref={playerRef}
src={src}
poster={thumbUrl}
loop
preload="none"
muted
playsInline
/>
</ThumbWrapper>
) : (
<SkeletonImage />
)}
</div>
);
};
export default VideoThumb;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment