Home > other >  React - HTML5 video element - toggle source depending on aspect ratio?
React - HTML5 video element - toggle source depending on aspect ratio?

Time:09-27

I have an app that needs to serve a 1:1 video OR a 16:9 video depending on viewport aspect ratio.

I can't just show/hide two <video> elements with CSS because I'm using videoRef.current to handle controls and it's a hat trick to implement that for two refs.

One foreseeable issue I can't wrap my head around would be if someone on desktop had their browser at a square-ish aspect ratio and was seeing the 1:1 video, then hit play and stretched their browser out to make it bigger and the video swapped out during playback. It would seem like there would endless issues trying to manage that behavior.

TLDR; What's the correct way to handle video in React w/ an HTML5 video tag?

CodePudding user response:

To handle video in HTML you would wrap your video around a source attribute. You can use a ternary operator to change the source depending on screen size or ratio. Something like this

import {useEffect} from 'react'
const vidRef = useRef();
import vid1 from './video1.mp4';
import vid2 from './video2.mp4';
const [width, setWidth] = useState()
cont [height, setWidth] = useState()

useEffect(() => {
    setWidth(window.innerWidth)
    setWidth(window.innerHeight)
}, [])

... (rest of code here)
return (
    <video ref={vidRef} controls>
        { width / height === 1 ? 
            <source src={vid1} type="video/mp4" />
        :
            <source src={vid2} type="video/mp4" />
        }
    </video>
)

Where CONDITION will be equal to the variable or boolean value that measures your screen size. You can set variables using the window.innerWidth or window.innerHeight and the condition could be something like width / height === 1 < Meaning 1:1 ratio. However you want to handle that, it should work!

  • Related