Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript StackNavigatonProps and Screen props in react-navigation v5

What is the best way to define type for screen's navigation prop, when screen is in different file that router? Let's say I have one file, in which I define routes:

//Router.tsx

type RootStackParamList = {
  Home: undefined;
  Profile: undefined;
}

const Stack = createStackNavigator<RootStackParamList>();

// Component rendering navigator
const Router = () => {
   .
   .
   .
}

Then I have the separate file for screen:

// Home.tsx


// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  "Home"
>;

type Props: {
  navigation: HomeScreenNavigationProp
}


const Home = ({navigation}: Props) => {
  .
  .
  .
}

Do I have to copy RootStackParamList over and over to every screen or create something like types.ts file and import it from there? Is there a better way to handle it? I am using navigation almost in every component.

like image 433
pafry Avatar asked Mar 16 '20 10:03

pafry


1 Answers

You can try this:

type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<
  navigation: StackNavigationProp<RootStackParamList, RouteName>,
  route: RouteProp<RootStackParamList, RouteName>
>
const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}
like image 159
user6343741 Avatar answered Nov 14 '22 01:11

user6343741