I want to have one video play after another video after one second automatically in react, I'm using state and setState to change the source of the video but it doesn't change the video. I'm at a loss.
import idle from './video/idle.mp4'
import intro from './video/Intro.mp4'
constructor(){
super()
this.state= {
vid: intro
}
}
componentDidMount(){
setTimeout (()=> {this.setState ({
vid: idle
}
)}, 1000) ;
}
render() {
return (
<div >
<div >
<video autoPlay={true} loop muted style={{width:"330px", height:"780px", paddingLeft:"10px", paddingTop:"220px"}}>
<source src={this.state.vid} type="video/mp4"/></video>
);
}
}
CodePudding user response:
First of all, make sure you import your videos outside your component.
Secondly, are you sure you can import these .mp4 files this way? Wouldn't it be better to call them directly by a relative path?
At least you could store two paths rather in string and assign these strings to your state
For example :
constructor(){
super()
this.idlePath = "/assets/videos/idle.mp4";
this.introPath = "/assets/videos/intro.mp4";
this.state= {
vid: ""
}
}
And then assign this.state.vid inside a componentDidMount method first then when the timeout is over you set the vid state to the introPath
CodePudding user response:
Solution with functional component:
import {
useEffect,
useState
} from "react";
const Component = () => {
const [ vidName, setVidName ] = useState("Intro");
useEffect(() => {
setTimeout (() => {
setVidName("idle");
}, 1000);
}, []);
return (
<video
autoPlay
loop
muted
style={{
width: "330px",
height: "780px",
paddingLeft: "10px",
paddingTop: "220px"
}}
>
<source
src={`./video/${vidName}.mp4`}
type="video/mp4"
/>
</video>
);
};
Class component:
import React from "react";
class Component extends React.Component {
constructor(props) {
super(props);
this.state = { vidName: "intro" };
}
componentDidMount() {
setTimeout (() => {
this.setState ({ vidName: "idle" });
}, 1000);
}
render() {
return (
<video
autoPlay
loop
muted
style={{
width: "330px",
height: "780px",
paddingLeft: "10px",
paddingTop: "220px"
}}
>
<source
src={`./video/${this.state.vidName}.mp4`}
type="video/mp4"
/>
</video>
);
}
}