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

Using Node.js variables outside of a function

I've been facing issues with passing my trends variable from its function into a renderer for my Pug template. It's proving to be quite challenging. var express = require('express'); ...

Showing a section of a DIV inside an iframe

I have implemented an HTML object in the following way: <object id="foo" name="foo" type="text/html" data="mypage.aspx"> </object> However, I do not want to display the entire content of mypage.aspx within the HTML object/iframe. In ...

Trigger Ajax only when a new row is added by the user in the SQL database using PHP Codeigniter

Avoiding frequent AJAX calls is necessary to prevent slowing down the POS system. We now prefer to trigger AJAX only when a user enters data from the frontend site, such as adding items to the cart. This helps in keeping the POS processes running smoothly ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Change the navbar brand in Bootstrap to be hidden on small screens like mobile devices

I am facing an issue with the navbar on my website where it expands in height when viewed on mobile devices due to not fitting into a single line. I have observed that if I remove the brand, it fits perfectly. However, I want to keep the brand visible on l ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Can an icon be included in Material UI's DataGrid headers when the sorting direction is not defined?

In the DataGrid's API of Material UI, you can see how to include a sort icon for ascending and descending directions. By default, these icons are shown as arrow up and arrow down symbols but can be customized using props. However, my project requires ...

What method can I use to ensure that the sidebar stays fixed at a particular div as the user continues to scroll down the

Is there a way to automatically fix the sidebar once the user scrolls down and hits the top of the .Section2? Currently, I have to manually enter a threshold number which can be problematic due to varying positions across browsers and systems. Fiddle htt ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

React material ui is not compatible with custom styles that are applied to components

I've developed a unique UserIcon Component that showcases an icon along with accompanying text. Take a look at the code snippet below: import React from "react"; import PropTypes from "prop-types"; import { withStyles, Avatar, Typography } from "@mat ...

"Troubleshooting a minor jQuery problem - update on current URL and refresh the page

I have developed a jQuery script that is designed to search through a webpage for specific text and then perform an action based on the findings. My query is straightforward. If I want to apply this script to a current website, such as www.google.com, how ...

Encountering an Error When Trying to Post to WebMethod Using AJAX

First Step: The initial step in this process involves defining a script on the home.aspx page. The script is as follows: function ShowCurrentTime() { var post = ({ method: "POST", url: "home.aspx/GetData", dataType: 'json ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Controller receiving empty object array from FormData

I am encountering an issue with my ajax call to the controller, where I am passing FormData() containing an array of objects and other properties. The list array that I pass seems to have 0 elements in the controller. Can anyone assist me with this problem ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

Unexpected restarts are occurring in a lengthy PHP script

I have a PHP script that I execute using the $.ajax() Javascript function: $.ajax({ type: "POST", url: "/myscript.php", data: $("#my-form").serialize() }); Details of myscript.php class myclass{ public function __construct(){ $i ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

Retrieve the information from FormData when the submit button is clicked

I am working on a form that has multiple input fields, including file inputs. I have integrated the jquery validate plugin and now I want to submit the form using ajax. HTML: <form method="post" name="addstudent" id="registrationform" enctype="multipa ...