Elaine
Elaine

Reputation: 403

How to stop React Player from playing when close modal?

I am using React Player npm install for React project. The video player is in a modal. How do I stop it from playing when the modal closes? Is there a ReactPlayer.stop() or a ReactPlayer.pause() type of functionality that I can add in my hideModal function?

<Modal show={this.state.show} handleClose={this.hideModal} >               
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' width='100%'
height='100%' />
</Modal> 

Upvotes: 4

Views: 10266

Answers (3)

Alexey Nazarov
Alexey Nazarov

Reputation: 2347

For me better works this example, key point to use together onPlay, onPause and playing prop

function VideoModal({ isShow, onClose, source }: any) {
  const [isPlaying, setPlaying] = useState(false)
  

  return (
    <AppModal 
      onClose={() => {
        setPlaying(false)
        onClose()
      }}
      isShow={isShow}
    >
        <ReactPlayer
          playing={isPlaying} 
          height='100%' 
          width="100%" 
          controls={true} 
          onPlay={() => setPlaying(true)}
          onPause={() => setPlaying(false)}
          url={source} 
        />
    </AppModal>
  )
}

Upvotes: 0

Cybernetic
Cybernetic

Reputation: 13334

viciousP has the correct answer, but I think it's worth showing the full code example so others can see exactly how this works.

Using the State Hook

import React, { useState } from 'react';
import ReactPlayer from 'react-player';

function Video() {

    const video_source = "https://vimeo.com/blahblah";

    function close_video() {
        setPlay(false)
    }

    const [play, setPlay] = useState(true);

    return(
        <ReactPlayer id="video" url={video_source} playing={play}/>
    )

}

export default Video;

Now you can programmatically stop the video from playing by calling close_video()

Upvotes: 1

viciousP
viciousP

Reputation: 520

If this.state.show returns Boolean value (true/false) you could control it through state like that:

<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' playing={this.state.show} width='100%' height='100%' />

Upvotes: 6

Related Questions