'React re-render restarting video
I have a react app with some complex view logic. There is one view where I need to have different parents and conditional renders. This causes my stream ref to be lost, or a video to restart. Is there anyway to set this up so my video instance can reach the new view state without restarting?
I've tried display none but it messes with my view, visibility hidden restarts the video.
here's a sandbox of my problem.
https://codesandbox.io/s/romantic-wood-qnn2x0?file=/src/App.js:0-1004
Solution 1:[1]
Here's one solution I thought of.
import { useState } from "react";
import React from "react";
import "./styles.css";
let flex = {
display: "flex"
};
let leftParent = {};
let VidInstance = React.forwardRef((props, ref) => {
return (
<div style={{ display: !props.mute ? "flex" : "none", width: 200 }}>
<video
controls=""
preload="none"
autoPlay
src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
width="200"
muted={props.mute}
></video>
</div>
);
});
export default function App() {
let [view, setView] = useState(false);
return (
<div className="App">
<flex style={flex}>
<leftParent style={leftParent}>
<Box />
<Box />
<VidInstance key="vid" mute={view} />
</leftParent>
<VidInstance key="vid" mute={!view} />
</flex>
<button onClick={() => setView(!view)}>view</button>
</div>
);
}
let Box = () => {
let boxStyle = {
width: "200px",
margin: "2px",
height: "100px",
background: "blue"
};
return <div style={boxStyle}></div>;
};
- Loading both
VidInstanceat same time to sync their play time. - Wrap
VidInstancewith a wrapperdivand give thatdivsame width as the video to reserve the empty space when your video goes hidden. - Pass
muteprop toVidInstanceto mute and hide inactive video.
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 | GCnomore |
