I am trying to take an html video without controls and customize them, I present the problem that I need my timeline to be constantly updated with the one currentTime
of the video, I use the hooks of the react api useRef
for the video useState
to change the one currentTime
of my component and useEffect
for trying to change the currentTime
code is as follows.
import React, { useRef, useState, useEffect } from 'react'
export const Video = ({ url }) => {
const player = useRef(null)
const [currentTime, setCurrentTime] = useState(0);
const [prueba, setPrueba] = useState(0);
useEffect(() => {
setCurrentTime(player.current.currentTime);
}, [prueba]);
const pruebita = () => {
setPrueba(prueba+1);
}
return (
<>
<video
ref={player}
autoPlay
src={url}
></video>
<div>{currentTime}</div>
<button onMouseDown={ pruebita }>clickeame muy seguido</button >
</>
)
}
The general idea is the same effect that is generated by having trial and trial, but without any component event.
I hope you can help me greetings.
I would not complicate myself and use a
setInterval
to synchronize the time with that of your React component, remember to destroysetInterval
it through the cleanup hook, it would be something like this:Sandbox, courtesy of milmal
Here is the demo. Thank you very much milmal for the reproducible code and also for adding the rounding of the decimals of the seconds.
update
I don't understand why it renders you infinitely, I suppose you are having a problem with a parent element... Look at this example, in which I use the same logic and it doesn't present any type of error: