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 sets npm install -g react-native-cli apart from utilizing npx react-native init <project name>?

**Can you explain the difference between setting up react-native-cli with npm install -g react-native-cli and init as opposed to using npx react-native init? As I was developing a React Native app, I encountered some strange errors. Initially, I set up m ...

Detecting When an Input has an :invalid Selector in Jquery

Here is the code snippet I am currently working with: HTML <input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" /> CSS input[type=text]:invalid { background-color: red; } Javascript $("[data-ty ...

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

The observable HTTP map appears to be more of a representation rather than a concrete entity

I seem to be struggling with understanding Typescript I expected the returned observable to have a method getTitle(), but it seems to be missing. Instead, I am getting an object that resembles AttachableContentModel without that particular method. What is ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

Unlock the power of dynamic routes in Reactjs with this comprehensive guide

Currently, I am delving into the world of Reactjs and Nextjs, specifically working on dynamic routes. To elaborate, I have a list of blogs that I would like to showcase in detail. For this purpose, I created a folder named "blogs" and nested a file called ...

Trouble displaying JSON data with AngularJS $http service

Struggling to retrieve json data. Initially, I created an ajax request that functioned properly in a regular html page but failed in my angular app. As a result, I decided to experiment with the built-in $http get function. Surprisingly, no errors are thro ...

What are the benefits of using Lifery Ajax URLs?

I'm currently using the Grails portlets plugin and I'm exploring how to properly route AJAX methods. It seems like <portlet:actionURL> is only able to map to methods that return models for GSPs, while <portlet:resourceURL> doesn&apos ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

What is the best way to move the Grid upward when the above content is not visible?

Let me demonstrate what I have been working on. Currently, I am creating a weather application to explore the functionalities of https://material-ui.com/. I am attempting to prototype an animation inspired by Google Flights, which can be seen here: https: ...

What is the reason for the 'scrollHeight' being considered 'undefined' in this particular scenario, and why did the iframe encounter an error when switching to the html-file?

This is my first time asking a question, so please forgive any mistakes... I am attempting to create a website using HTML, CSS, and JavaScript on my Raspberry Pi with Apache2. I have written a script for an automatic iframe height function based on the co ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Begin setting up a React hook within a class-oriented component

During my transition from a function-based component to a class-based one, I encountered an error. How can I initialize a hook in a class component without triggering this error? Click here to view the error message. Exploring Paperbase Material UI impo ...

Manage and display data in Vue.js using the CLI

I'm currently developing a form where users can input data and I need to display that data on another page using Vue.js Below is the form I have created: <form id="main-contact-form" class="contact-form r ...