Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Refresh a Screen in React Native?

I know similar questions have been asked here already, but I just can't get it to work! Im using iframe to embed a YouTube player in one of my screens (using Stack Navigator). I created an array with some YouTube Links/IDs, which are then being randomised and imported into the player, so each time I navigate to that particular screen, a random video starts playing! Now I want to add a 'play next video' button! I tried updating the screen 'key' and use different methods of forceUpdating the screen, but nothing seems to work right! Does anyone have an Idea?

Heres my code:

note that rn there is the playpause function in the 'next vid' button


 
import React, { useState, useCallback, useRef } from "react";
import { Button, View, Alert, Text } from "react-native";
import YoutubePlayer from "react-native-youtube-iframe";
import {NeuView, NeuButton} from 'react-native-neu-element';
import { set } from "react-native-reanimated";



//example vids
const videos = [
  'iNQAp2RtXBw',
  'AJqiFpAl8Ew',
  'IdoD2147Fik',
]

const randomVideo = () =>
videos[Math.floor(Math.random() * videos.length)];



export default function FunnyVideos() {
  
  const [playing, setPlaying] = useState(true);
  const [videoId, setRandomVideoId] = useState(randomVideo());

  
  
 function pauseOrPlay() {
    return ((
      setPlaying(!playing)
    ), []);
  }




  return (
    <View  alignItems = 'center' >
      <NeuView style = {{marginTop: '15%'}}  width = {330} height = {200} color = '#f2f2f2' borderRadius = {20} >
        <View overflow = 'hidden' height = {169}  style = {{position: 'relative', marginTop: 0}} justifyContent = 'center' alignContent = 'center' borderRadius = {10}> 
          <YoutubePlayer
          
            height={'100%'}
            width={300}
            videoId = {videoId}
            play = {playing}
            
            />
       </View>
     </NeuView>
    
    <View flexDirection = 'row'>
      <NeuButton style = {{marginTop: 60}}  width = {250}  height = {100} color = '#f2f2f2' title={playing ? "pause" : "play"} onPress = {pauseOrPlay} borderRadius = {20}>
        <Text>
        {playing ? "pause" : "play"}
        </Text>
      </NeuButton>
      
    </View>
      <NeuButton style = {{marginTop: 45}} width = {250}  height = {100} color = '#f2f2f2' title={playing ? "pause" : "play"} onPress = {pauseOrPlay}  borderRadius = {20}>
        <Text>
          Next Video
        </Text>
      </NeuButton>

    
    </View>
  ); 
}
like image 640
Swifter Avatar asked Sep 02 '25 14:09

Swifter


1 Answers

Change the onPress of Next Video to () => setRandomVideoId(randomVideo())

like image 145
maltoze Avatar answered Sep 05 '25 04:09

maltoze