The TouchableOpacity function is triggered every time I press on the Textinput

Every time I press on a text input field, the login function is called

This is the touchable statement:

<TouchableOpacity
     style={InputFieldStyle.submitButton}
     onPress={this.login(this.state.email, this.state.password)}>
          <Text style={InputFieldStyle.submitButtonText}>Submit Me</Text>
</TouchableOpacity>

The login function definition:

login = (email, pass) => {
     alert(`Email: ${email} Password: ${pass}`);
};

I am currently working on Textinput in my expo project

Is there a way to prevent the login function from being called every time, or am I doing something wrong here?

Answer №1

In the code snippet provided, the login() function is implemented as an arrow function and does not require binding using bind(). The issue lies with the onPress prop of the TouchableOpacity component. This prop should be assigned a function that will be executed when the button is pressed.

The current problem arises from directly invoking the login() function within the render() method and passing its return value (undefined) to the button. Consequently, the login() function gets called every time the render() method is triggered.

To rectify this issue, modify the code from:

<TouchableOpacity onPress={this.login(this.state.email, this.state.password)} {...otherProps}>

to

<TouchableOpacity onPress={() => {this.login(this.state.email, this.state.password)}} {...otherProps}>

Answer №2

While the accepted answer may currently work, it is not considered a best practice. Embedding bindings in your render function can complicate code readability in the future.

Additionally, passing the email and password as parameters when they are already stored in the state is unnecessary and leads to data duplication which can cause confusion in more complex code scenarios.

A cleaner solution to address this issue would be:

login = () => {
  const { email, password } = this.state
  alert(`Email: ${email} Password: ${password}`);
}

//render
<TouchableOpacity onPress={this.login}>

Answer №3

Utilize the TextInput component from 'react-native' in place of InputField and ensure that only one submission is made for both email and password by employing setState. For a demonstration, refer to this . Implementing this approach will assist in resolving your current issue.

Answer №4

Transform it into an arrow function as shown below. . onPress={()=>this.login()} . That way, the function will only be triggered when a button is pressed.

Answer №5

If you're encountering an issue with the code snippet

onPress={this.login(this.state.email, this.state.password)

To resolve this problem, you need to utilize the bind() method and include this keyword as the first parameter like so:

onPress={this.login.bind(this, this.state.email, this.state.password)}

For further information on the bind() method, check out this link: Read more about bind() method

However, there is no need to pass the email and password as parameters; you can directly access them from the state

Modify your method to appear as follows:

login = () => {
  const { email, password } = this.state;
  alert(`Email: ${email} Password: ${password}`);
}

Update your touchable component to look like:

<TouchableOpacity onPress={this.login}>

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

Obtain the contents of a div element from a specified URL

Having trouble with my side menu and hide/show div functionality. When I click the back button, the content of the previously viewed div does not appear. How can I fix this issue? I've looked into using jQuery pushstate but it's still confusing t ...

Managing Datatable with a dynamic header and data is an essential skill that can greatly enhance

I am struggling to handle the Datatable for different header column names with data from my controller. I am passing table headers column name and table data value from my controller. Although I am able to access columns in json within the drawCallback f ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

What could be causing php://input to refuse my large file uploads?

I have been searching extensively on the internet to figure out how to enable chunked large file uploads for my Symfony2 application. To simplify things, I created a separate test program from the rest of my application. The sole purpose of this test progr ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

After selecting a delivery method, the checkout feature on opencart 1.5.6.4 is malfunctioning

Check out my online shop at store.suhaskhamkar.in. I've set it up using OpenCart version 1.5.6.4, but I'm facing an issue with the checkout process. It seems to get stuck at step #4, which is the Delivery method selection. Upon checking the conso ...

The optimal functioning of Ajax is conditioned upon the successful upload of the HTML page onto my server

Is it normal that the below code returns an "error" message when the HTML file is not uploaded to my server? I find it odd because once I do upload it, everything works perfectly. Can anyone explain why this happens? <head> <script src="http:// ...

JavaScript truthy values referring to numbers

According to the rules outlined below: Falsy: false 0 (zero) '' or "" (empty string) null undefinded NaN (e.g. the result of 1/0) Truthy: Anything else I'm puzzled as to why, in the tests that follow, only the number 1 is considered "tr ...

When capturing photos using h5 on iOS devices, the browser may experience a flash back issue

I have been searching Baidu and Google for a while now, but I still haven't found a solution. Here is the specific issue: When using h5 to take photos on iOS systems, the browser flashes back. HTML Code <img src="xxx" onclick="sta ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

Struggling to create a BMI Calculator using JS, the result is consistently displaying as 'NaN'

Having trouble creating a BMI Calculator using JavaScript. The issue I'm facing is that the calculation always returns 'NaN'. I've tried using parseInt(), parseFloat(), and Number() but couldn't solve the problem. It seems that the ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Is it possible to retrieve a trimmed svg image and store it on a device using react-native-svg in React Native?

I have a modified image that I want to save in my device's gallery. Can someone please guide me on how to achieve this? My project is developed using TypeScript. Modified image: https://i.stack.imgur.com/LJOY9.jpg import React from "react"; ...

Error message: ParseError: Received an unexpected character '<' while running tests using AVA

Initially encountering an issue within the project built on nuxt, I attempted to resolve it by creating a new project using vue-cli and re-installing AVA via npm. However, this did not have any effect on the problem at hand. Upon researching, I came across ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Generate a dynamic JSON object using JavaScript and then deliver it back

I'm dealing with a function that is supposed to return a JSON object in this format: this.sampleFunction = (x, filename) => { if (x.isPresent()) { return { 'result': true }; } else { return { 'result&apos ...