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

React Navigation: How to create a reusable NavButton with type checks

$
0
0

I'm building a React Native app with Typescript and I'm fairly new to Typescript for React Navigation. I'm trying to simply create a reusable NavButton that can be used like this:

<NavButton     icon="arrow"     to={tab: "Tab1", screen: "Screen 2", params: { param1: "Param1" }} />

My navigation structure is as follows:

RootTabNavigator    -Tab1: Tab1StackNavigator        -Screen1        -Screen2    -Tab2: Tab2StackNavigator        -Screen1        -Screen2        -Screen3

Here is my NavButton component:

type Tab = keyof RootTabParamList;type Screen = ??not sure what type to make this??type: Params ??not sure what type to make this??interface NavButtonProps extends IconButtonProps {    to: {        tab: Tab;        screen: ??how do I dynamically set this type based on the Tab provided??        params: ??how do I dynamically set this type based on the Screen provided??    }};export default function NavIconButton(props: NavButtonProps): JSX.Element {    const { to, ...rest } = props;    const navigation = useNavigation();    function handlePress(): void {        navigation.navigate(to);    };    return <IconButton onPress={handlePress} {...rest} />;};

So, in VSCode, navigation.navigate() is already being type checked correctly as I followed the documentation and included the following in my navigation.d.ts file:

declare global {    namespace ReactNavigation {        interface RootParamList extends RootTabParamList {}    }};

But where I'm getting stuck is that I don't know how to take that argument type that is required by navigation.navigate() and apply that to my "to" prop?


Viewing all articles
Browse latest Browse all 6290

Trending Articles



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