'How to get DOM element properties before they render in ReactJS
I have a div in which I am playing a video using a video tag. The problem is before playing the video I am calculating the ratio between the div and video and I am getting undefined if I console the out in the browser console.
const App = () => {
const vRef = useRef<HTMLVideoElement>(null);
const dRef = useRef<HTMLDivElement>(null);
const [videoHeight, setVideoHeight] = useState<number | null>();
const [containerHeight, setContainerHeight] = useState<number | null>();
const [newHeight, setNewHeight] = useState<number | null>();
useEffect(() => {
const reference = dRef.current;
if(reference){
const oldHeight: number = reference.getBoundingClientRect().height
setContainerHeight(oldHeight);
if(containerHeight && videoHeight){
setNewHeight(containerHeight/videoHeight)
}
}
},[]);
console.log(newHeight);
return <div ref={dRef}>
<video className='video-player' ref={vRef}>
<source src={"..."} />
</video>
</div>
}
I am getting undefined on newHeight. I need to calculate this ratio before playing the video.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
