To navigate to a screen when onInitialized is called in React Navigation, you'll need to use a reference to the navigation object. Here’s how you can modify your NavigationContainer and FoodDataProvider components to achieve this:
First, ensure that you have a navigation ref to control your navigator.
Use the onReady prop of the NavigationContainer to hook into the initialization of the navigator.
Within the onReady callback, you can call the navigate function to go to the "Main" screen.
Here is a refined version of your code:
javascript
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { navigationRef } from './RootNavigation'; // Assuming you have set up this file for navigation references.
import MainScreen from './MainScreen'; // Your main screen component
import OtherScreen from './OtherScreen'; // Any other screen components
const Stack = createStackNavigator();
function App() {
const onInitialized = () => {
navigationRef.current?.navigate('Main');
};
return (
<NavigationContainer
ref={navigationRef}
onReady={onInitialized}
>
<Stack.Navigator initialRouteName="OtherScreen">
<Stack.Screen name="Main" component={MainScreen} />
<Stack.Screen name="OtherScreen" component={OtherScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Ensure you have a proper navigation reference (e.g., RootNavigation.js) set up like this:
javascript
import { createNavigationContainerRef } from '@react-navigation/native';
export const navigationRef = createNavigationContainerRef();
export function navigate(name, params) {
if (navigationRef.isReady()) {
navigationRef.navigate(name, params);
}
}
Explanation:
Navigation Container Setup: The NavigationContainer component now includes the onReady prop. This will call onInitialized once the navigator is ready.
Navigation Reference: The navigationRef from RootNavigation.js provides a way to control navigation imperatively.
onInitialized Function: This function is responsible for navigating to the "Main" screen when the navigation container is first initialized.
Screens: Make sure that you have relevant screens (e.g., MainScreen, OtherScreen) defined and imported correctly.
Following this setup, once the NavigationContainer is ready, it will immediately navigate to the "Main" screen.