Reputation: 91
I have an array of videos which are displayed by Bootstrap carousel embedded in a modal dialog box. The video doesn't start playing automatically when the modal is show but you need to click on it and it will start playing. My issues is that on slide change the current video playing won't pause. So this is what i need to achieve, to pause current video when the user changes slides(back or forth). How can I do this? BTW I am using React Js.
Any help is greatly valued.Thanks.✌️
Below is my Video Carousel component.
import React, { Component } from "react";
import 'bootstrap/dist/css/bootstrap.min.css';
import Carousel from 'react-bootstrap/Carousel';
import "../carousel.css";
export default class VideoCarousel extends Component {
constructor(props) {
super(props);
this.videoRef = React.createRef();
// this.state = {
// index: 0,
// isPlaying: false
// }
}
render(){
return(
<div>
<Carousel activeIndex={this.index} onSelect={this.handleChange} interval={null} className="carousel">
{this.props.items.map((item, index) => {
return (
<Carousel.Item key={index}>
<video
ref = {this.videoRef}
className="videoItem"
controls="controls"
>
<source src={item.src} type="video/mp4"/>
</video>
<Carousel.Caption>
{/* <h2>{item.title}</h2> */}
</Carousel.Caption>
</Carousel.Item>
);
})}
</Carousel>
</div>
)
}
}
Upvotes: 1
Views: 1261
Reputation: 13078
You are using the same reference for all the items. After running the map function this.videoRef will be equal to the last element of the array.
this.videoRef = React.createRef([]);
Iterate over the elements and assign the reference based on the index value:
<Carousel activeIndex={this.index} onSelect={this.handleChange} interval={null} className="carousel">
{this.props.items.map((item, index) => {
return (
<Carousel.Item key={index}>
<video
ref = {el => this.videoRef.current[index] = el}
...
>
...
</Carousel.Item>)
})}
</Carousel>
To pause the video use the element reference at specific position:
this.videoRef.current[index].pause();
You can handle the controls functions on componentDidMount/componentWillUnmount
this.videoRef = React.createRef(null);
Assign the reference:
export default class VideoCarouselItem extends Component {
constructor(props) {
super(props);
this.videoRef = React.createRef();
}
render(){
<Carousel.Item key={this.props.key}>
<video
ref = {this.videoRef}
...
>
</Carousel.Item>
}
}
Then through properties pass the info you need.
Upvotes: 2