Core utilities for building navigators in React Native applications
—
Navigation container and context components that manage navigation state, distribute it throughout the app component tree, and provide theming and lifecycle management.
Container component that holds the navigation state and should be rendered at the root of the app, wrapping all navigators and screens.
/**
* Root navigation container that manages navigation state
* @param props - Navigation container configuration
* @returns Navigation container component
*/
function BaseNavigationContainer(props: NavigationContainerProps): React.JSX.Element;
interface NavigationContainerProps {
/** Initial navigation state for deep linking or state restoration */
initialState?: InitialState;
/** Callback invoked when navigation state changes */
onStateChange?: (state: NavigationState | undefined) => void;
/** Callback invoked when navigation tree mounts and is ready */
onReady?: () => void;
/** Callback invoked when navigation action is not handled */
onUnhandledAction?: (action: NavigationAction) => void;
/** Theme object for UI styling */
theme?: ReactNavigation.Theme;
/** Child navigator components and screens */
children: React.ReactNode;
}
type InitialState = Partial<NavigationState> | {
routes: { name: string; params?: object; state?: InitialState }[];
};Usage Examples:
import React from 'react';
import { BaseNavigationContainer } from "@react-navigation/core";
// Basic setup
function App() {
return (
<BaseNavigationContainer>
<RootNavigator />
</BaseNavigationContainer>
);
}
// With state persistence and callbacks
function AppWithPersistence() {
const [initialState, setInitialState] = useState();
const [isReady, setIsReady] = useState(false);
useEffect(() => {
const restoreState = async () => {
try {
const savedState = await AsyncStorage.getItem('navigation_state');
if (savedState) {
setInitialState(JSON.parse(savedState));
}
} finally {
setIsReady(true);
}
};
restoreState();
}, []);
if (!isReady) {
return <SplashScreen />;
}
return (
<BaseNavigationContainer
initialState={initialState}
onStateChange={(state) => {
AsyncStorage.setItem('navigation_state', JSON.stringify(state));
}}
onReady={() => {
console.log('Navigation ready');
}}
theme={isDark ? darkTheme : lightTheme}
>
<RootNavigator />
</BaseNavigationContainer>
);
}Reference object for imperative navigation access outside of component tree.
/**
* Create a navigation container ref for imperative access
* @returns Ref object with navigation methods
*/
function createNavigationContainerRef<ParamList extends ParamListBase = ParamListBase>():
NavigationContainerRefWithCurrent<ParamList>;
interface NavigationContainerRef<ParamList extends ParamListBase = ParamListBase> {
/** Navigate to a screen */
navigate<RouteName extends keyof ParamList>(
name: RouteName,
params?: ParamList[RouteName]
): void;
/** Go back to previous screen */
goBack(): void;
/** Dispatch navigation action */
dispatch(action: NavigationAction): void;
/** Reset navigation state to provided state */
resetRoot(state?: PartialState<NavigationState> | NavigationState): void;
/** Get the current navigation state */
getRootState(): NavigationState;
/** Get the currently focused route */
getCurrentRoute(): Route<string> | undefined;
/** Get current screen options */
getCurrentOptions(): object | undefined;
/** Check if navigation is ready to handle actions */
isReady(): boolean;
/** Add event listener */
addListener<EventName extends keyof NavigationContainerEventMap>(
type: EventName,
callback: (e: NavigationContainerEventMap[EventName]) => void
): () => void;
}
interface NavigationContainerRefWithCurrent<ParamList extends ParamListBase = ParamListBase>
extends NavigationContainerRef<ParamList> {
current: NavigationContainerRef<ParamList> | null;
}Usage Examples:
import { createNavigationContainerRef } from "@react-navigation/core";
// Create ref
const navigationRef = createNavigationContainerRef();
function App() {
return (
<BaseNavigationContainer ref={navigationRef}>
<RootNavigator />
</BaseNavigationContainer>
);
}
// Use ref for imperative navigation
function navigateFromOutsideComponent() {
if (navigationRef.isReady()) {
navigationRef.navigate('Profile', { userId: '123' });
}
}
// Listen to navigation events
navigationRef.addListener('state', (e) => {
console.log('Navigation state changed', e.data.state);
});
// Reset navigation state
function resetNavigation() {
navigationRef.resetRoot({
index: 0,
routes: [{ name: 'Home' }],
});
}React context that provides the navigation prop to child components.
/**
* Context that holds navigation prop for a screen
*/
const NavigationContext: React.Context<NavigationProp<ParamListBase> | undefined>;Usage Examples:
import { NavigationContext } from "@react-navigation/core";
import { useContext } from 'react';
// Access navigation context directly
function MyComponent() {
const navigation = useContext(NavigationContext);
if (!navigation) {
throw new Error('NavigationContext not found');
}
return (
<Button
title="Navigate"
onPress={() => navigation.navigate('Profile')}
/>
);
}
// Provide navigation context manually
function CustomProvider({ navigation, children }) {
return (
<NavigationContext.Provider value={navigation}>
{children}
</NavigationContext.Provider>
);
}React context that provides the route prop to child components.
/**
* Context that holds route prop for a screen
*/
const NavigationRouteContext: React.Context<RouteProp<ParamListBase> | undefined>;Usage Examples:
import { NavigationRouteContext } from "@react-navigation/core";
import { useContext } from 'react';
function MyComponent() {
const route = useContext(NavigationRouteContext);
if (!route) {
throw new Error('NavigationRouteContext not found');
}
return (
<View>
<Text>Current route: {route.name}</Text>
<Text>Route key: {route.key}</Text>
</View>
);
}Provider component for theme context, enabling consistent theming throughout navigation components.
/**
* Provider component for theme context
* @param props - Theme provider props
* @returns Theme provider component
*/
function ThemeProvider(props: ThemeProviderProps): React.JSX.Element;
interface ThemeProviderProps {
/** Theme object to provide to child components */
value: ReactNavigation.Theme;
/** Child components that will receive theme */
children: React.ReactNode;
}
interface Theme {
/** Whether the theme is dark mode */
dark: boolean;
/** Theme color palette */
colors: {
/** Primary color for highlights and active states */
primary: string;
/** Background color for screens */
background: string;
/** Background color for cards and surfaces */
card: string;
/** Text color */
text: string;
/** Border color */
border: string;
/** Notification color for badges and alerts */
notification: string;
};
}Usage Examples:
import { ThemeProvider } from "@react-navigation/core";
const lightTheme = {
dark: false,
colors: {
primary: '#007AFF',
background: '#FFFFFF',
card: '#F2F2F2',
text: '#000000',
border: '#E5E5E5',
notification: '#FF3B30',
},
};
const darkTheme = {
dark: true,
colors: {
primary: '#0A84FF',
background: '#000000',
card: '#1C1C1E',
text: '#FFFFFF',
border: '#38383A',
notification: '#FF453A',
},
};
function App() {
const [isDark, setIsDark] = useState(false);
return (
<ThemeProvider value={isDark ? darkTheme : lightTheme}>
<BaseNavigationContainer>
<RootNavigator />
</BaseNavigationContainer>
</ThemeProvider>
);
}
// Accessing theme in components
function ThemedButton({ title, onPress }) {
const theme = useTheme();
return (
<TouchableOpacity
style={{
backgroundColor: theme.colors.primary,
padding: 12,
borderRadius: 8,
}}
onPress={onPress}
>
<Text style={{ color: theme.colors.background }}>
{title}
</Text>
</TouchableOpacity>
);
}Provider for prevent remove context, enabling prevention of navigation under certain conditions.
/**
* Provider for prevent remove functionality
* @param props - Prevent remove provider props
* @returns Prevent remove provider component
*/
function PreventRemoveProvider(props: PreventRemoveProviderProps): React.JSX.Element;
interface PreventRemoveProviderProps {
/** Child components */
children: React.ReactNode;
}Usage Examples:
import { PreventRemoveProvider, usePreventRemove } from "@react-navigation/core";
function FormScreen() {
const [hasChanges, setHasChanges] = useState(false);
return (
<PreventRemoveProvider>
<FormWithPreventRemove
hasChanges={hasChanges}
onChangesMade={() => setHasChanges(true)}
onChangesSaved={() => setHasChanges(false)}
/>
</PreventRemoveProvider>
);
}
function FormWithPreventRemove({ hasChanges, onChangesMade, onChangesSaved }) {
usePreventRemove(hasChanges, ({ data }) => {
Alert.alert(
'Unsaved Changes',
'You have unsaved changes. Are you sure you want to leave?',
[
{ text: 'Stay', style: 'cancel' },
{ text: 'Leave', onPress: () => navigation.dispatch(data.action) }
]
);
});
return (
<View>
<TextInput onChangeText={onChangesMade} />
<Button title="Save" onPress={onChangesSaved} />
</View>
);
}Component to create independent navigation trees that don't interfere with the main navigation hierarchy.
/**
* Component to create independent navigation trees
* @param props - Independent tree props
* @returns Independent navigation tree component
*/
function NavigationIndependentTree(props: NavigationIndependentTreeProps): React.JSX.Element;
interface NavigationIndependentTreeProps {
/** Child components forming the independent tree */
children: React.ReactNode;
}Usage Examples:
import { NavigationIndependentTree } from "@react-navigation/core";
function App() {
return (
<BaseNavigationContainer>
<MainNavigator />
{/* Independent navigation tree for modals */}
<NavigationIndependentTree>
<ModalNavigator />
</NavigationIndependentTree>
</BaseNavigationContainer>
);
}
// Use case: Modal with its own navigation
function ModalWithNavigation() {
return (
<NavigationIndependentTree>
<ModalStack.Navigator>
<ModalStack.Screen name="ModalHome" component={ModalHome} />
<ModalStack.Screen name="ModalSettings" component={ModalSettings} />
</ModalStack.Navigator>
</NavigationIndependentTree>
);
}Other context components for specialized navigation functionality.
/**
* Context for navigation container reference
*/
const NavigationContainerRefContext: React.Context<NavigationContainerRef<any> | undefined>;
/**
* Context for navigation helpers
*/
const NavigationHelpersContext: React.Context<NavigationHelpers<any> | undefined>;
/**
* Context for current render state (internal)
*/
const CurrentRenderContext: React.Context<any>;
/**
* Context for prevent remove functionality
*/
const PreventRemoveContext: React.Context<{
preventedRoutes: Record<string, { routeKey: string; callback: Function }>;
addPreventRemove: (routeKey: string, callback: Function) => void;
removePreventRemove: (routeKey: string) => void;
} | undefined>;These contexts are typically used internally by the navigation system or for advanced custom navigator implementations.
Install with Tessl CLI
npx tessl i tessl/npm-react-navigation--core