Error in Typescript: _this2.onClick is not a callable function

For react-native development, I rely on typescript. In my project, List and ListItem components come from NativeBase, with ListItem resembling a TouchableOpacity.

...
public onClick = () => this.props.navigation.navigate("NextScreen");
public _renderRow = (item: any) {
    return (
        <ListItem onPress={() => this.onClick()}>
             ...
        </ListItem>
    );
}
public render() {
   return(
        <List
            dataArray={this.data}
            renderRow={this._renderRow}
        />
   );
}

Upon clicking an item, I encounter the following error:

_this2.onClick is not a function. (In '_this2.onClick()', '_this2.onClick' is undefined)

I suspect the issue lies in the fact that the onClick() function has not been properly bound to the component class. Does typescript handle this binding automatically?

What steps should I take to resolve this problem?

Answer №1

In order to ensure the method is properly connected to the components class, you will need to use the bind function:

public onClick() { 
  this.props.navigation.navigate("NextScreen"); 
}
public _renderRow(item: any) {
    return (
        <ListItem onPress={this.onClick}>
             ...
        </ListItem>
    );
}
public render() {
   return(
        <List
            dataArray={this.data}
            renderRow={this._renderRow.bind(this)} // <---- Here
        />
   );
}

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 is the best way to set up configurations for node modules?

I have a module called mymodule which includes configuration options such as foo, bar, and two functions named f1 and f2. My goal is to initialize this module with default values in one client application, while passing different defaults in another clien ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Trying out a function named on Sinon.js spy

Currently, I am utilizing SinonJS to verify that my controller is calling certain methods within my view. Specifically, I am aiming to confirm that the addSeat method is invoked with the value of testSeat. Despite my efforts in the code snippet below, I am ...

What is causing the continuous appearance of null in the console log?

As part of my JavaScript code, I am creating an input element that will be inserted into a div with the id "scripts" in the HTML. Initially, I add a value to this input field using JavaScript, and later I try to retrieve this value in another JavaScript fu ...

How can one use TypeScript to return a subclass instance within a static function of a base class?

Below is the code snippet: class BaseElement { public static create<T extends typeof BaseElement>(this: T ): InstanceType<T> { this.createHelper(); const r = new this(); return r; } public static createHelpe ...

What is the method for typing an array of objects retrieved from realmDB?

Issue: Argument type 'Results<Courses[] & Object>' cannot be assigned to the parameter type 'SetStateAction<Courses[]>'. Type 'Results<Courses[] & Object>' lacks properties such as pop, push, reverse, ...

Filtering JSON data by the keys of a Backbone.js model

I have a standard backbone collection that I am working with. (function($){ var DataModel = Backbone.Model.extend({}); var DataCollection = Backbone.Collection.extend({ model: DataModel, url: 'assets/path_data.json' }); var data ...

Troubleshooting Problems with Node.js and MongoDB Integration during the .save() Process

Welcome to my sample website, powered by a basic Node.js server. I have managed to set up user creation and posting functionalities successfully. However, there seems to be an issue with saving user data to the database as the saved user object cannot be l ...

Chrome's rendering of CSS flex display shows variations with identical flex items

I am facing an issue with my flex items where some of them are displaying incorrectly in Chrome but fine in Firefox. The problem seems to be with the margin-right of the rectangle span within each flex item, along with the scaling of the text span due to f ...

Is it possible to incorporate a button and a click event into this JavaScript function?

For over a day, I've been attempting to include three functionalities in this code, but have yet to succeed. 1° My goal is to insert a button on this page. I've attempted to create a standard button using HTML and CSS, but the fireworks displa ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

React's Dynamic Table fails to rerender when updated values are placed in the same row and under the same header

Here is the table generated by my functional component: <table class="table"> {/* Consonant Table */} <tr> <th colSpan="2">---</th> {headersPOA. ...

Is there a way to input the Sno data into the database in ascending order?

function table_insert(lease_ids){ var lease_id=lease_ids+1; var table = document.getElementById('table_data123'), rows = table.getElementsByTagName('tr'), i, j, cells, customerId; for (i = 0, j = rows.le ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...

Unable to retrieve the unique identifier for this item

When attempting to retrieve the current ID of an item in a table by clicking the Purchase button and using console.dir, it only displays the first element. I have also tried console.dir for this.id but it returns nothing. function listProducts() { ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

How can Mbox content be loaded dynamically according to the selected option in a dropdown menu, instead of loading it when

I am looking to enhance my asp.net page by adding a new MBox that will be triggered based on the dropdown selected value. Unlike other MBoxes on the page that load on page load, I want this new MBox to dynamically pass custom parameters to T&T when a val ...

JavaScript error caused by incorrect JSON parsing

Encountering Another Issue. Here's the Relevant Code: if(localStorage.getItem("temporaryArray")){ var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray")); }else{ var temporaryArray = []; } Essentially, what this code snippet ...

Interop-require-default is nowhere to be found in the babel-runtime

I'm really stuck on how to resolve this error. I've tried searching online and followed the suggestions given by others. I even went as far as deleting 'node_modules' and reinstalling, but nothing seems to be working. The specific erro ...