Azam Alvi
Azam Alvi

Reputation: 7055

How to redirect to other Screen without pressing button/link in React Native

I am using @react-navigation/native library for navigation. Now scenario is that I want to navigate to other screen after in setTimeout. I don't want to stack the page so I'm not usning native-stack. I have tried below code but it is not redirecting to HomeScreen

App.tsx

import React, { useEffect } from 'react';
import { Text, View } from 'react-native';
import { createNavigationContainerRef } from '@react-navigation/native';
import HomeScreen from './src/screens/HomeScreen';

const navigationRef = createNavigationContainerRef();
function navigate(name, params) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

export default function App() {

  // after 3 seconds it should redirect to HomeScreen
  useEffect(() => {
    setTimeout(() => {
      navigate(HomeScreen, {})
      //navigate('HomeScreen', {})
    }, 3000)
  })

  return (
    <View><Text>Hello</Text></View>
  );
}

Upvotes: 1

Views: 3016

Answers (1)

enzou
enzou

Reputation: 316

You have to use a state to know what screen to render, when that state change you must change screen.

If you dont wanna stack the screen you can use the reset, another way you must use an if to decide it.. for example to first case using reset https://reactnavigation.org/docs/5.x/navigation-actions/#reset

import { CommonActions } from '@react-navigation/native';

export default function App() {
  const navigation = useNavigation()

  // after 3 seconds it should redirect to HomeScreen
  useEffect(() => {
    setTimeout(() => {
      navigation.dispatch(
       CommonActions.reset({
         index: 1,
         routes: [{ name: 'Home' }],
       })
     );
    }, 3000)
  }, [])

  return (
    <View><Text>Hello</Text></View>
  );
}

For second example (and correct IMHO)

export default function App() {
  const [changeScreen, setChangeScreen] = useState(false)

  // after 3 seconds it should redirect to HomeScreen
  useEffect(() => {
    setTimeout(() => {
      setChangeScreen(true)
    }, 3000)
  }, [])

  return (
    changeScreen ? 
    <Home /> :
    <View><Text>Hello</Text></View>
  );
}

Upvotes: 1

Related Questions