I have a loop of MP4 videos in my React application. However, when I click a button, I want another MP4 video to start playing. But as soon as I click the button, there’s a momentary white screen for about 1 second before the other video starts playing. How can I prevent this white screen from appearing?
// VideoPlayer.jsx
import { useContext, useEffect, useState } from "react";
import { VideoContext } from "../context/VideoContext";
const VideoPlayer = () => {
const { activeVideo, videos, setActiveVideo } = useContext(VideoContext);
const [loop, setLoop] = useState(null);
const isLoop = () => {
if (activeVideo === videos.cam1Fixed || activeVideo === videos.cam2Fixed) {
setLoop(true);
} else {
setLoop(false);
}
};
const onEnded = () => {
if (!loop) {
setActiveVideo(videos.cam2Fixed);
}
};
useEffect(() => {
isLoop();
}, [activeVideo]);
return (
<div className="w-full h-full absolute top-0 left-0 z-[-1]">
<video
onEnded={onEnded}
className="w-full h-full object-cover"
src={activeVideo}
autoPlay
muted
loop={loop}
></video>
</div>
);
};
export default VideoPlayer;
// ChangeCamButton.jsx
import { useContext } from "react";
import { VideoContext } from "../context/VideoContext";
const ChangeCamButton = () => {
const { setActiveVideo, videos } = useContext(VideoContext);
const changeCam = () => {
setActiveVideo(videos.cam1Transition);
};
return (
<button onClick={changeCam} className="text-white text-xl bg-red-600 rounded-md p-3 bg-opacity-90 hover:bg-red-500 transition-all">
Change Camera
</button>
);
};
export default ChangeCamButton;
// VideoContent.jsx
import { createContext, useState } from "react";
import videos from "../utils/index";
const VideoContext = createContext();
const VideoProvider = ({ children }) => {
const [activeVideo, setActiveVideo] = useState(videos.cam1Fixed);
return (
<VideoContext.Provider value={{ activeVideo, setActiveVideo, videos }}>
{children}
</VideoContext.Provider>
);
};
export { VideoContext, VideoProvider };
// App.jsx
import "./App.css";
import VideoPlayer from "./components/VideoPlayer";
import { VideoProvider } from "./context/VideoContext";
import ChangeCamButton from "./components/ChangeCamButton";
function App() {
return (
<VideoProvider>
<VideoPlayer />
<ChangeCamButton />
</VideoProvider>
);
}
export default App;