I have a row of thumbnails that are supposed to play a video when I hover over them, and stop when I mouse out of the thumbnail. As of right now, only the last thumbnail plays it’s video when I hover, all the other ones are frozen. But if I hover over one of the frozen videos, then back to the working video, the working video will have moved forward as if I was hovering over it the whole time.
This is my component
import React from 'react'
import { projectlist } from '../../projectlist'
import { useRef } from 'react'
import './Projects.css'
export default function Projects() {
const playerRef = useRef<any>()
function onMouseOver(){
console.log('playerRef',playerRef)
playerRef.current.play();
}
function onMouseOut(){
playerRef.current.pause();
}
return (
<div className='projects-container'>
{projectlist.map((video)=>{
return(
<div className='project-image' key={video.video_id} onMouseOver={onMouseOver} onMouseOut={onMouseOut}>
<video ref={playerRef} muted loop>
<source src={video.test} type='video/mp4' />
</video>
<img src={video.image}/>
</div>
)
})}
</div>
)
}
Here is the CSS incase it is relevant
.project-image{
position: relative;
img{
position: relative;
width: 100%;
height: 100%;
z-index: 1;
}
video{
position: absolute;
opacity: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: 0;
}
&:hover{
video{
z-index: 2;
opacity: 1;
}
}
}
I used this video as a reference: https://www.youtube.com/watch?v=UIX0DSaNOjI&ab_channel=ColbyFayock around the 15:30 mark is where I followed the useRef guide.
2
Answers
It is simple. You have only one
ref
and multiple videos. How can the system or anyone identify which video the ref is for. Also, all your videos have only one listener formouseOut
andmouseOver
each.You need a list of
ref
s, one for each video. Or you need a ref, which can hold multiple values.Now, you also have to modify your functions to ensure that there is an identifier for each video.
You can also follow the video and create a
ref
andmethod
for each video seperately.I give you an example for your reference: