Is it possible to transfer functions between components in React-Native, even if they are located in separate files?

In one of my classes, there's a method that I need to call. Specifically, the

() => this.props.navigation.navigate('Detail')
. Originally, I had a button on each FeedCard for navigation, but it seemed messy so I switched to using touchable opacity instead.

HomeScreen.js

class HomeScreen extends Component {
    state = { }
    render() {
        return(
            <Root>
                <List>
                    <FeedCard />
                    <FeedCard doThis={() => this.props.navigation.navigate('Detail')} />
                    <FeedCard />
                    <FeedCard />
                    <FeedCard />
                    <FeedCard />
                    <FeedCard />
                </List>
            </Root>
        )
    }
};

Can functions be passed in React Native just like how I did with doThis()?

FeedCard.js

function FeedCard({doThis}) {
    return (
        <Root>
            <TouchableOpacity onPress={doThis}>
                <FeedCardHeader />
                <CardContainer>
                    <CardContentText>
                        {text}
                    </CardContentText>
                </CardContainer>
                <FeedCardBottom />
            </TouchableOpacity>
        </Root>
    )
};

When I directly added the function to the onPress() in the <TouchableOpacity> component, it gave me the error

TypeError: undefined is not an object (evaluating '_this.props')
, which made me wonder if passing a function similar to my attempt above was even possible. Unfortunately, the code above doesn't navigate as intended. I am aware that navigation works because when I placed it in an onPress() within a <Button> on the same page as the HomeScreen, it worked perfectly.

Answer №1

Implement a blank function in another Feedcard component

<FeedCard doThis={() => { }} />
<FeedCard doThis={() => this.props.navigation.navigate('Detail')} />
<FeedCard doThis={() => { }} />
<FeedCard doThis={() => { }} />
<FeedCard doThis={() => { }} />
<FeedCard doThis={() => { }} />
<FeedCard doThis={() => { }} />

If you prefer not to pass it, follow the instructions below

function FeedCard({doThis}) {
    return (
        <Root>
            <TouchableOpacity onPress={() => ÏdoThis}>
                <FeedCardHeader />
                <CardContainer>
                    <CardContentText>
                        {text}
                    </CardContentText>
                </CardContainer>
                <FeedCardBottom />
            </TouchableOpacity>
        </Root>
    )
};

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

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...

Unit testing a React component by using the `renderToString` method

Context My React application is built using the React Starter Kit. In the server.js file, components are rendered using renderToStaticMarkup and then passed to the Html component, which includes it using dangerouslySetInnerHTML as shown here. I am facing ...

The checkbox in angular js is failing to be marked as selected

<tr ng-repeat="languages in samln"> <td> <span>{{languages.emplang}}</span> </td> <td> <input type="checkbox" name="checkbox1-" id="sp1" value="false" style="margin-left:40px;" ng-model="languages ...

Show whether the day is even or odd with the JavaScript getDay object

I'm currently working on a task where I need to show the text "Even Day" if the day of the month is 2, 4, 6..., and "Odd Day" for days such as 1, 3, 5, and so on. I attempted to achieve this by setting up an array linked to the getDay object, but unfo ...

What steps should I take to set up search paths for node modules in Code Runner within Visual Studio Code?

Just recently, I embarked on a Javascript course and successfully configured my Visual Studio Code to run JavaScript. Check out the code snippet that I came up with: const prompt = require('prompt-sync')(); var fname = prompt("First name please : ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

jQuery MaskMoney - position input at the start of the field

Check out this jsfiddle I created to showcase the issue I'm facing. Whenever I click on the input field, the cursor automatically goes to the end. This means that I have to start typing cents before dollars, which is not the behavior I want. My desire ...

AngularJS Filtering - content within html elements

I struggle with filtering and would like to create a personalized filter using the following scenario: When I make a call to a service, I receive a JSON object with HTML that is combined with another string, resulting in messy HTML. My goal is to extract ...

What is causing my text to not appear in a single line?

Can someone help me figure out why my register and login options are overlapping? I'm pretty new to this so it might be a simple fix. Also, I'm trying to get the dropdown menu to appear right below the login text, but I'm facing some issues ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

Is it safe to use static variables in JavaScript across multiple threads?

Currently, I am developing a node.js web server that is responsible for handling large payloads, computations, and copying tasks. One specific requirement involves creating a deep copy of a substantial object: const largeObject = { bla: "bla" } / ...

What are the best methods for resizing a video without altering its aspect ratio?

function initializeConstructor(props) { super(props); this.state = { screenWidth: Dimensions.get('window').width, heightScaled: null, }; } <View style={styles.videoView}> <Video sourc ...

Slickgrid's scrollRowIntoView function isn't behaving as anticipated

Here is my code that utilizes the scrollRowIntoView function. I am making use of the resizer to adjust the grid's length to match the browser window. Currently, I have hardcoded a number as an example, but eventually, I will fetch the record to be scr ...

Node.js Discord.js SQL leaderboard troubleshooting

I have successfully developed a Discord bot with message listeners that interacts with a MySQL database to store data based on specific events. Below is the code snippet I use to increment the score by +1 when a message is sent in the channel: // If a ...

Issue encountered while retrieving information from JSON structure

My data is stored in a JSON file named info.json. [ {"employee": {"name":"A", "salary": "324423"}}, {"employee": {"name":"B", "salary": "43111"}}, {"employee": {"name":"C", "salary": "43434"}}, {"employee": {"name":"D", "s ...

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

Generating TypeScript user-defined type guards from interfaces programmatically

Within my Angular2 project, I have defined an Interface called GridMetadata: grid-metadata.ts export interface GridMetadata { activity: string; createdAt: object; totalReps: number; updatedAt: object; } In my Service, there is a public method na ...

Tips for Re-positioning the Manage Password Window in a Browser Using CSS

I am facing an issue with the Caps Lock key indication on my login page. When the Caps Lock key is on, a tooltip should be displayed below the password field. However, when the browser's "manage passwords" bubbles are shown, the tooltip gets hidden be ...