2

I have two videos from https://www.npmjs.com/package/react-native-video I do not have the controls active, my intention is to activate and deactivate the videos by pressing buttons. I do it with states, my problem is that when I press a button to pause or play a video, all of them play, not just one.

I have a list of videos in a JSON and iterate through all of them.

Here is a snippet of my code:

const [paused, setPaused] = useState(false);

const playVideo = () => {
    setPaused(!paused);
}

{videos.map((video) => (
    <Video
        source={{ uri: video.video }}
        rate={1.0}
        volume={1.0}
        resizeMode="cover"
        style={styles.video}
        paused={paused}
        onEnd={() => setPaused(true)}
    />
    {paused && (
        <View style={styles.videoPause}>
            <Text style={styles.title}>{video.titulo}</Text>
            <Text style={styles.description}>{video.descripcion}</Text>
            <TouchableOpacity style={styles.playButton} onPress={() => playVideo()}>
                <CustomIcon name="play" size={90} color={'#fff'} />
            </TouchableOpacity>
        </View>
    )}

))}

2 Answers2

0

The problem is with your state, you should make a component to wrap the Video and manage play/pause state in there. This way you can control every video individually.

miknoup
  • 204
  • 2
  • 5
0

First create a component which has independent state and not global as you have it here.

Example:

export default function VideoPlayer(props) {
  const { styles, video } = props
  const [paused, setPaused] = useState(false)

  const playVideo = () => {
    setPaused(!paused)
  }

 return (
  <View>
    <Video
    paused={paused}
    rate={1.0}
    resizeMode="cover"
    source={{ uri: video.video }}
    style={styles.video}
    volume={1.0}
    onEnd={() => setPaused(true)}
  />

  {
    paused && (
      <View style={styles.videoPause}>
        <Text style={styles.title}>{video.titulo}</Text>
        <Text style={styles.description}>{video.descripcion}</Text>
        <TouchableOpacity style={styles.playButton} onPress={() => playVideo()}>
          <CustomIcon color="#fff" name="play" size={90} />
        </TouchableOpacity>
      </View>
    )
  }
}
)

and then render it in your page like this:

{videos.map((video) => <VideoPlayer styles={...YOUR_STYLES} video={video}/>}

You can also declare the styles inside the component if you prefer but then you wont need to pass them as props.