Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to use the same component in different screens in a navigator with typescript?

$
0
0

In my React Native (Expo) app I want to have a FriendsScreen and a OthersScreen in a MaterialTopTabNavigator. It's kind of a social media app. All of the user's friends are displayed in a list on the FriendsScreen. The OthersScreen shows users who have not yet been added as friends. However, since the two screens look almost the same, I wanted to use the same component for both screens (To reuse code and not have to copy and paste code when making changes).

That's why my navigator looks like this:

import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';const TopTab = createMaterialTopTabNavigator<TopTabParamList>();export default function TopTabNavigator() {    return (<TopTab.Navigator><TopTab.Screen name="Friends" component={UsersScreen} /> // Friends: UsersScreen<TopTab.Screen name="Others" component={UsersScreen} /> // Others: UsersScreen</TopTab.Navigator>    );}

In order to be able to display small differences between the two screens, I wanted to give the UserScreen a route param named type.

export type TopTabParamList = {  Friends: { type: 'Friends' | 'Others' };  Others: { type: 'Friends' | 'Others' };};

In the UsersScreen I want to use the type param to determine whether the UsersScreen should fetch the friends of the user or strangers from my server. But since I'm using Typescript, I don't know how to type the route prop.

interface Props {  route: RouteProp<TopTabParamList, /*'Friends' or 'Others'?*/>;}

Somehow I have the feeling that my problem should be solved differently...

Final question:

How can I have 2 tabs (screens) in a MaterialTopTabNavigator that use the same component in which I can determine which screen this component now represents, while everything is correctly typed with Typescript?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>