Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function:

App.tsx

import React, {useState} from 'react';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import Navigator from './Components/Navigator';
import { Root } from 'native-base';
import * as Font from 'expo-font';
import AppLoading  from 'expo-app-loading';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import rootReducer from './Store/Reducers/Reducers';

const store = createStore(rootReducer);

export default class App extends React.Component {
  constructor(props) {
    super(props);
   this.state = { loading: true };
}

async componentDidMount() {
   await Font.loadAsync({
   Roboto: require('native-base/Fonts/Roboto.ttf'),
   Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
 });
 this.setState({ loading: false });
}

render(){
  if (this.state.loading) {
    return (
      <Root>
        <AppLoading />
      </Root>
    );
  }
  else {
    return (
      <Provider store={store}>
        <Root>
           <NavigationContainer>
             <Navigator/>
            </NavigationContainer>
        </Root>
      </Provider>          
    );
  }
 }
}

Navigator.tsx

import React from 'react'
import { createStackNavigator } from '@react-navigation/stack'
import Login from '../Views/Login'
import Home from '../Views/Home'

const Stack = createStackNavigator();

const Navigator= () =>{
  return (
        <Stack.Navigator>
            <Stack.Screen name="Login" component={Login}  options={{headerShown:false}}/>
            <Stack.Screen name="Home" component={Home} options={{title:'Home.'}}/>
        </Stack.Navigator>
  );
}

export default Navigator;

Login.tsx (I'm trying to send props on Button function...)

import React, {useState} from 'react'
import {Text, TextInput, View, Image } from 'react-native'
import {Button, Toast, Content} from 'native-base'
import {Auth} from '../Services/Auth/AuthService'

const Login=({navigation})=>{
   const [userName, setUserName] =useState('');
   const [password, setPassword] =useState('');
   const [resultLog, setResultLog] = useState('');

   return( 
     <View>
        <TextInput placeholder="Username..." defaultValue={userName} onChangeText={txt=> setUserName(txt)} />
        <TextInput placeholder="Password..." defaultValue={password} onChangeText={txt=> setPassword(txt)}  secureTextEntry={true}/>
        <Button primary style={{width:115, height:45, marginBottom:15}} onPress={()=> ValidateFields(userName, password, navigation)? navigation.navigate('Home') : Toast.show({
            text: resultLog})}> 
            <Text style={{color:'white'}}>Login</Text> 
        </Button>
        <Button bordered  onPress={()=> navigation.navigate('Register')}> 
            <Text style={{color:'red'}}>Register </Text> 
        </Button>
     </View>
   );
}

async function ValidateFields(userName:string, password:string, navigation:any){
   await Auth.LoginUser({nick:userName, password: password}, navigation);
   //...
}

export default Login;

AuthService.tsx (I'm trying to receive props and then use dispatch for Redux...)

export const Auth={
    LoginUser,
}

interface IAuthData{
   nick : string,
   password : string
};

async function LoginUser(AuthData:IAuthData, navigation: any){
  try{
      console.log(navigation);
      let response = await fetch('http://localhost/user/Login/authentication', 
                                                                    {method: 'POST',
                                                                    headers: {
                                                                    Accept: 'application/json',
                                                                    'Content-Type': 'application/json'
                                                                    },
                                                                    body: JSON.stringify(AuthData)
      });

      let json = await response.json();      
      if(response.status==200){
          navigation.dispatch(//...code here);
      }
  }catch(err){
     console.error(err);
  }
}

When attempting to press the Login Button, an error message is displayed:

undefined is not an object (evaluating '_this.props')

Answer №1

In the functional component, you have used this.props, which is meant for class components only. To correct this, modify your code as follows:

const Login=(props)=>{

   const {navigation} = props; // include this line 
   .....

   return( 
     <View>
        .....
        // In place of "this.props", use "props" only
       <Button onPress={()=> ValidateFields(userName, password, props)? navigation.navigate('Home') : Toast.show({
            text: resultLog})}> 
            <Text style={{color:'white'}}>Login</Text> 
        </Button>
     </View>
   );
}

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

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

Unlocking the Potential of JavaScript Proxy: Clearing Out an Array Object

Examining the JavaScript Proxy code snippet below: const queue = new Proxy([], { get: (target, property) => { return target[property]; }, set: (target, property, value) => { target[property] = value; this._pro ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

What is the best way to pass a variable to the chrome.tab.create function?

Is there a way to pass a variable to the `chrome.tabs.create` function? I am currently working on setting up event listeners for my anchors, but I am faced with a challenge as I am creating them within a for loop: for (var i = 0; i < links.length; i++) ...

What is the method for establishing session or cookie in an HTTPS request to a specific URL?

When making an HTTPS GET request in Node.js to a specific URL, it is necessary to include the session cookie. In this case, I already have the value of the cookie that needs to be sent. var URL = require('url-parse'); var appurl = "https://test ...

Is submitting data through ajax giving you trouble?

As a beginner in PHP with no knowledge of Javascript, I have been relying on tutorials to complete my JS tasks. Despite trying various solutions from StackOverflow, I have yet to achieve success! My goal is to update database values by clicking the ' ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

TS2339: The 'contacts' property is not found within the 'Navigator' type

I am currently developing a contacts application that utilizes the Apache Cordova plugins for contacts. However, when attempting to run the npm run bundle command for my application, I encountered the error mentioned in the title above. Can anyone guide me ...

How can a script be properly embedded into an HTML document?

Currently, I am facing an unusual issue with the script tags in my Django project. My layout.html file includes Jquery and Bootstrap in the head section. Using Jinja, I extended layout.html to create a new file called main.html. In main.html, I added a new ...

Discovering instances of a specific string within a larger string

My goal is to customize the default behavior of the alert function. Below is the code I am using: window.alert=function(txt) { waitOk='wait'; setMsgBox(txt); btnMsgOk.focus(); } However, I need this functionality to vary ba ...

Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :) I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is ...

Using WebdriverIO with Angular to create end-to-end tests in TypeScript that involve importing classes leads to an error stating "Cannot use import statement outside a module."

I am facing an issue while trying to set up a suite of end-to-end tests using wdio. Some of the tests utilize utility classes written in TypeScript. During the compilation of the test, I encountered the following error: Spec file(s): D:\TEMP\xx& ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

Utilizing JS datepicker for multiple input fields sharing a common class

After trying to implement the js-datepicker plugin from https://www.npmjs.com/package/js-datepicker, I ran into an issue. I have multiple input fields in which I want to use the same date picker, so I assigned them all the class 'year'. Unfortuna ...

Storing JSONP data in a variable: Tips and Tricks

Having an issue with storing JSONP data into variables and using it as input for a Google Pie Chart. Consider the following: Data in test.json: { "name": "ProjA", sp": 10, "current": 20 } The goal is to retrieve the SP value. Attempted solution usin ...

Issue with Jquery UI draggable positioning in a specific Reveal.js slide

While my jQuery draggable feature works flawlessly in a simple HTML page without the presence of reveal.js, I encounter an issue within my reveal.js presentation where I utilize embed=true [utilizing only a portion of the full page for each slide]. When i ...

Traversing an array of objects using D3.js

I'm attempting to create a row of bars that are all the same height and width based on their titles. I have an array of 100 objects, each with a key called results containing another array of 20 objects. This means I should end up with a row of 2000 b ...