Reputation: 7
I try to make video player in reactjs
Here my code
import "./App.css";
import React, { Component, useState } from "react";
import ReactPlayer from "react-player";\
function App() {
const [myvideo, setMyvideo] = useState("");
const arrayqueue = [
{
singer: "The Valley",
videoname: "video/video_test.mp4",
},
{
singer: "My Friend",
videoname: "video/video_test2.mp4",
},
{
singer: "Say wow",
videoname: "video/video_test3.mp4",
},
];
return (
<div>
<ReactPlayer url={myvideo} controls={true} />
<div className="queue-size" id="style-1">
{arrayqueue.map((item, index) => {
return (
<div
className="row-queue"
key={index}
onClick={() => setMyvideo(item.videoname)}
>
<div className="column-queue">{item.singer}</div>
</div>
);
})}
</div>
</div>
);
}
export default App;
I'm sucess make onclick in the queue and set video to ReactPlayer , my question is how to make ReactPlayer automatic play the next from queue , so the ReactPlayer have 2 option , if I don't click in queue , the video will autoplay from queue, Thank you :)
Upvotes: 0
Views: 4291
Reputation: 4519
ReactPlayer has a prop called onEnded
(more info here) that can be used to trigger a callback function when the current media finishes playing.
You could keep track of the index for the video that is currently playing and set a callback to loop through your array of videos.
I updated your code and added comments to the lines I changed, so you can see an example:
import "./App.css";
import React, { Component, useState } from "react";
import ReactPlayer from "react-player";\
function App() {
const [myvideo, setMyvideo] = useState("");
// New state to save index of currently playing video
const [myvideoIndex, setMyvideoIndex] = useState(0);
const arrayqueue = [
{
singer: "The Valley",
videoname: "video/video_test.mp4",
},
{
singer: "My Friend",
videoname: "video/video_test2.mp4",
},
{
singer: "Say wow",
videoname: "video/video_test3.mp4",
},
];
// Callback function that plays next video (or goes back to first video)
const playNext = () => {
const nextIndex = myvideoIndex + 1
if (nextIndex >= arrayqueue.length) {
setMyvideo(arrayqueue[0])
setMyvideoIndex(0)
} else {
setMyvideo(arrayqueue[nextIndex])
setMyvideoIndex(nextIndex)
}
}
// When click, set the video and the current index
const handleClick = (item, index) => {
setMyvideo(item.videoname)
setMyvideoIndex(index)
}
return (
<div>
<ReactPlayer url={myvideo} controls={true} onEnded={playNext} />
<div className="queue-size" id="style-1">
{arrayqueue.map((item, index) => {
return (
<div
className="row-queue"
key={index}
onClick={() => handleClick(item, index)}
>
<div className="column-queue">{item.singer}</div>
</div>
);
})}
</div>
</div>
);
}
export default App;
Upvotes: 1