Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React navigation 5 error Binding element 'navigation' implicitly has an 'any' type.ts

I am new to react-native. I am trying to implement navigation using react-navigation 5. I have two screens Home and profile. These both components have received a navigation prop but typescript is giving me follwoing error

Binding element 'navigation' implicitly has an 'any' type.ts(7031)

How to get rid of this error.

Thank you in advance

NOTE - I am using typescript

App.tsx

import 'react-native-gesture-handler';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

import Home from './screens/home'

const App  = () => {

  const ProfileScreen = ({}) => {
    return <Text>This is Jane's profile</Text>;
  };
  
  return (
    <NavigationContainer>

    <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={Home}
          
        />
        <Stack.Screen name="Profile" component={ProfileScreen} />
      </Stack.Navigator>

  </NavigationContainer>

  );
};

Home.tsx

import React from 'react';
import { Button } from 'react-native';


const Home = ({navigation}) =>{ // error

  return (
    <Button
    title="Go to Jane's profile"
    onPress={() =>
      navigation.navigate('Profile', { name: 'Jane' })
    }
  />
  )
  
}

export default Home;
like image 352
pratik jaiswal Avatar asked Jul 28 '20 10:07

pratik jaiswal


1 Answers

Typescript has no idea of the navigation type.

To just get rid of this error, you can type the navigation prop as any (not advisable btw) like so:

/*doing this will make you lose type safety*/
const Home = ({navigation}: {navigation: any}) => {
 return ...
}

Recommended approach

Looking at the docs https://reactnavigation.org/docs/typescript/ we can see we need to create an object type with mappings for route name to the params of the route, then pass this object type as a generic to the createStackNavigator function.

In the screens, we need to import the corresponding type from the navigator which in you case is the StackNavigator. This type takes 2 generics: a params list object type and the name of the current route.

// in your case

// App.tsx
import { createStackNavigator } from '@react-navigation/stack';

type RootStackParamList = {
  Home: undefined, // undefined because you aren't passing any params to the home screen
  Profile: { name: string }; 
};

const Stack = createStackNavigator<RootStackParamList>();


// Home.tsx
import { StackNavigationProp } from '@react-navigation/stack';
type ProfileScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  'Home'
>;

type Props = {
  navigation: ProfileScreenNavigationProp;
};

const Home = ({navigation}: Props) =>{
  return ...
}
like image 188
its_tayo Avatar answered Nov 05 '22 17:11

its_tayo