In React Native with TypeScript, you can use the Stack.Screen
component provided by react-navigation
to create a screen component that can receive parameters. Here’s an example of how to create a Stack.Screen
component with parameters in TypeScript:
import React from 'react';
import { StackNavigationProp } from '@react-navigation/stack';
import { RouteProp } from '@react-navigation/native';
import { StackParamList } from './StackParamList'; // define your own StackParamList type
type Props = {
navigation: StackNavigationProp<StackParamList, 'ScreenName'>;
route: RouteProp<StackParamList, 'ScreenName'>;
};
const ScreenName: React.FC<Props> = ({ route }) => {
const { param1, param2 } = route.params;
// Use the parameters to render the screen
return (
<View>
<Text>Parameter 1: {param1}</Text>
<Text>Parameter 2: {param2}</Text>
</View>
);
};
export default ScreenName;
In this example, StackParamList
is a custom type that defines the available screens in your navigation stack. You can define it like this:
export type StackParamList = {
ScreenName: { param1: string; param2: number };
// Add more screens here as needed
};
This defines a StackParamList
with a screen named ScreenName
that expects two parameters: param1
(a string) and param2
(a number). You can then navigate to this screen and pass the parameters like this:
navigation.navigate('ScreenName', { param1: 'hello', param2: 123 });