Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get video height on mounting before rendering layout?

I’m rendering two tabs on a page. The tab content is a video player and other elements under it. The problem is that when switching tabs the layout glitches. Anyone can help me with that?

To solve this I tried with no success (on mounting height is 0):

  const [videoHeight, setVideoHeight] = useState<number | null>(0);

  useEffect(() => {
    const { height } = videoElement.current?.getBoundingClientRect() as DOMRect;
    setVideoHeight(height);
  }, []);

      <CardMedia
        component={'video'}
        src={videourl}
        ref={videoElement}
        height={videoHeight}
        width={'100%'}
      />

Here’s a codesandbox: https://codesandbox.io/s/video-player-mw4c98?file=/src/App.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

UPD

I tried useLayoutEffect instead of useEffect with no success as well. I believe that is because video is not fully loaded at that moment.

>Solution :

I think the issue is not with height jumping from 0 to the actual height. The height is correctly set. The thing is video elements have a default black poster that appears in a bit after you mount them on the page. I’m not sure if there is a native or better way to work around it, but it seems some people have found a solution by setting a white poster instead. If you don’t want to rely on the body’s background color (which is usually white), you could go with a transparent png as the poster. Here is the original question/answer I’m referring to:
Remove black background from html5 video. Appears for a second

I tested it here:
https://codesandbox.io/s/video-player-forked-5jxd7m

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading