'changing video source in useEffect based on language change

I'm trying to play different videos on language change. however the same video always plays,

useEffect(() => {
console.log("language changed: ", i18n.language);

vidSrc2.current.setAttribute(
  "src",
  require(`../assets/video/${i18n.language}/vid.mp4`)
);
window.addEventListener("langChange", () => {
  vidSrc2.current.setAttribute(
    "src",
    require(`../assets/video/${i18n.language}/vid.mp4`)
  );
 });
}, [i18n.language]);

<video
      ref={videoRef2}
      style={{
        objectFit: "cover",
        width: "100vw",
        height: window.screen.availHeight === 1080 ? "74vh" : "77vh"
      }}
      controls
      controlsList="nofullscreen nodownload"
      preload="true"
      disablePictureInPicture
    >
      <source
        ref={vidSrc2}
        type="video/mp4"
      />
    </video>

any help would be appreciated.



Solution 1:[1]

import {useEffect, useState} from 'react'
import Modal from '../../modal/modal-video'
import router, { useRouter } from "next/router";

const useModal = () => {
    const [isShown, setIsShown] = useState<boolean>(false);
    const toggle = () => setIsShown(!isShown);
    return {
        isShown,
        toggle,
    };
};

const PlayBtn = () => {
    const { isShown, toggle } = useModal();
    const [video, setVideo ] = useState('');
    const [title, setTitle] = useState('')
    const router = useRouter()
    useEffect(() => {
        if(router.locale == 'nl-BE'){
            const url = "/video/nl.mp4"
            setTitle("Test in Dutch")
            setVideo(url)
        }else if (router.locale == 'en-US'){
            const url = "/video/eng.mp4"
            setTitle("Test in English")
            setVideo(url)
        }else {
            const url = "/video/fr.mp4"
            setTitle("Test in French")
            setVideo(url)
        }
    })
  
    return(
        <>
        <div className="h-28 w-28 bg-white rounded-full playBtn mt-20 md:mt-0">
            <button type="button" onClick={toggle}><img src="../../img/play-button.png" alt="" /></button>
        </div>
        <Modal 
            isShown={isShown}
            hide={toggle}
            headerText={title}
            modalContent={
                <iframe width="100%" height="100%"
                    src={video}>
                </iframe>
            }
        />
        </>
    )
}

export default PlayBtn

This is how I did it. I work with useState and check with router.locale which locale is currently selected.

You can even set your src in the setVideo('/video/nl.mp4'), without using a const url.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1