Home > Software design >  How to get DOM element properties before they render in ReactJS
How to get DOM element properties before they render in ReactJS

Time:02-05

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.

CodePudding user response:

You aren't getting the height of the video element anywhere in that code. (And there are some minor type issues.)

Instead, be sure to get the height of each element, and then do the calculation; see *** comments:

import React, { useRef, useState, useEffect } from "react";

const App = () => {
    const vRef = useRef<HTMLVideoElement>(null);
    const dRef = useRef<HTMLDivElement>(null);
    const [videoHeight, setVideoHeight] = useState<number>();           // *** Removed `| null`,
    const [containerHeight, setContainerHeight] = useState<number>();   // *** with no arg `undefined`
    const [newHeight, setNewHeight] = useState<number>();               // *** is automatically added

    useEffect(() => {
        // *** Get the DOM elements
        const div = dRef.current;
        const video = vRef.current;
        if (div && video) { // (this is probably unnecessary in runtime terms, but
                            // it makes TypeScript happy when we use them below)
            // *** Get the height of each of them
            const divHeight = div.getBoundingClientRect().height;
            setContainerHeight(divHeight);
            const videoHeight = video.getBoundingClientRect().height;
            // *** Get the ratio (note: "newHeight" seems an odd thing to call a _ratio_)
            setNewHeight(containerHeight / videoHeight);
        }
    },[]);

    console.log(newHeight);

    return <div ref={dRef}>
        <video className='video-player' ref={vRef}>
            <source src={"..."} />
        </video>
    </div>;
};
  •  Tags:  
  • Related