navigating through different pages on a react-native application

While building my app in react-native, I encountered some issues with setting up the navigation. I referred to the react-native documentation for guidance, specifically this navigation guide. The guide mentioned passing an object named "navigation" to your components, like so:

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

However, I found that it didn't explain what exactly this "navigation" object was. I assumed it had something to do with creating a stack, similar to my navigation setup below:

const Stack = createNativeStackNavigator();

const Navigation = () => {
  return (
    <NavigationContainer>
      
      <Stack.Navigator initialRouteName='Login'>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Schedule" component={ScheduleBody} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default Navigation;

In my implementation, I also passed the "navigation" object to my pages where needed, as shown below:

const Header = ({navigation}) => {
  const [hasWorkout, setHasWorkout] = React.useState(false);

  useEffect(() => {
    setHasWorkout(false);
  }, []);

  const toggleActiveWorkout = () => {
    setHasWorkout(!hasWorkout);
  };

  const handleCalendar = () => {
    
    navigation.navigate('Schedule');
  };

  // Rest of the code...
};

After setting up my navigation, I integrated it into my app.tsx file like this:

const Stack = createNativeStackNavigator();

const App = () => {
  const [loggedIn, setLoggedIn] = React.useState(false);

  const checkLoggedIn = async () => {
    const user = await AsyncStorage.getItem('user');
    if (user) {
      setLoggedIn(true);
    }
  };

  useEffect(() => {
    
    checkLoggedIn();
  }, []);
  return (
      <NavigationContainer>
        <View style={styles.container}>
          <Header navigation={Stack}/>
          <ScrollView>
            {loggedIn ? <Body /> : <Login />}
          </ScrollView>
          <Footer navigation={Stack} />
        </View>
      </NavigationContainer>
  );
};

Despite my efforts, I kept encountering the error message:

Binding element 'navigation' implicitly has an 'any' type.
I suspect there might be an issue with how I'm handling navigation in app.tsx. Any advice or assistance would be greatly appreciated.

Answer №1

When working with navigation in Typescript, it's important to define the routes and parameters you'll be using. For example:

type AuthStackParams = {
    Home: undefined;
    Schedule: undefined;
}

Then, when defining your Stack, make sure to specify these types:

const SomeNavigation = CreateStackNavigator<AuthStackParams>();

Remember that InitialRouteName must be a valid route from your stack.

When using the useNavigation() hook, be sure to type it like this:

const navigation = useNavigation<StackNavigatorProp<AuthStackParamList>>()

This will provide hints about your navigation destination. If navigating to another stack, consider creating a global navigation function or typing out root navigator props to avoid implicit any types.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The implementation of race in React Redux Saga is proving to have negligible impact

I have implemented the following saga effect: function* loginSaga() { const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate'); let logoutTimeout: number; if (!logoutTimeoutCreationDate || + ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...

In Angular, the object may be null

click here for image Encountering an error message stating that Object is possibly 'null' when utilizing querySelector and addEventListener in Angular. ...

Expo project refusing to launch

I encountered an issue with my expo project not starting when I attempted to use npm start. The versions I am using are: Expo-cli: 3.20.5 Node : 12.16.3 I followed these steps: 1. Ran expo init project 2. Selected the blank template 3. Executed expo ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

What sets apart `lib.es6.d.ts` from `lib.es2015.d.ts` in TypeScript?

I'm a bit confused about ES6 and ES2015. In TypeScript, there are two type declarations available for them: lib.es6.d.ts and lib.es2015.d.ts. Can someone explain the difference between these two? And which one is recommended to use? ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

The Angular Library encountered an error stating that the export 'X' imported as 'X' could not be found in 'my-pkg/my-lib'. It is possible that the library's exports include MyLibComponent, MyLibModule, and MyLibService

I have been attempting to bundle a group of classes into an Angular Library. I diligently followed the instructions provided at: https://angular.io/guide/creating-libraries: ng new my-pkg --no-create-application cd my-pkg ng generate library my-lib Subseq ...

I'm struggling to figure out the age calculation in my Angular 2 code. Every time I try to run it,

Can anyone assist me with calculating age from a given date in Angular? I have written the following code but I keep getting undefined in the expected field. This is Component 1 import { Component, OnInit, Input } from '@angular/core'; ...

Batch requesting in Typescript with web3 is an efficient way to improve

When attempting to send a batch request of transactions to my contract from web3, I encountered an issue with typing in the .request method. My contract's methods are defined as NonPayableTransactionObject<void> using Typechain, and it seems tha ...

Is there any advice for resolving the issue "In order to execute the serve command, you must be in an Angular project, but the project definition cannot be located"?

Are there any suggestions for resolving the error message "The serve command requires to be run in an Angular project, but a project definition could not be found."? PS C:\angular\pro\toitsu-view> ng serve The serve command requires to be ...

There is no index signature containing a parameter of type 'string' within the type '{ appointments: { label: string; id: number; minWidth: number; }[]; }'

Just getting started with React and Typescript. I'm attempting to extract data from the configuration file based on the input(props), but it seems like Typescript is throwing errors. Any suggestions on how to tackle this issue? config.json { "t ...

Is there a method available that functions akin to document.getelementbyid() in this specific scenario?

Currently, I am tackling a project that involves implementing a search function. My initial step is to ensure that all input is converted to lowercase in order to simplify SQL calls. However, I have encountered a challenge that is proving difficult for me ...

The specified property cannot be found on the object type in a Svelte application when using TypeScript

I am attempting to transfer objects from an array to components. I have followed this approach: https://i.stack.imgur.com/HHI2U.png However, it is indicating that the property titledoes not exist in this type. See here: https://i.stack.imgur.com/VZIIg.pn ...

"String representation" compared to the method toString()

Currently, I am in the process of writing unit tests using jasmine. During this process, I encountered an issue with the following code snippet: let arg0: string = http.put.calls.argsFor(0) as string; if(arg0.search(...) This resulted in an error stating ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...

Monitoring customer's credit card operations in React Native

Looking for suggestions on reliable APIs or services that enable an application to monitor a user's credit card and debit card transactions. Any recommendations? ...

Can you set up a mechanism to receive notifications for changes in an array variable in Angular?

I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime() operator from RxJs, but I need this to be triggered by changes in an array that I have defined. Here is the scenario: export c ...

TypeScript encounters a problem when attempting to concatenate arrays with different signature overloads

I encountered the following error message: There is an issue with overloading. Overload 1 of 2, '(...items: ConcatArray<{ title: string; width: number; dataIndex: string; render: (level: string) => Element; }>[]): { title: string; width: nu ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...