Using a function as a prop in React Native can result in an error, specifically when trying to call an 'onPress' function which is not recognized as a valid function and is instead seen as

Hey there! I'm facing an issue while trying to trigger an action in the parent component from a child component using props. One of the props in the child is a function that should update the parent's state when a button is pressed, triggering a re-render. However, instead of success, I encounter this error:

TypeError: onPress is not a function. (In 'onPress(event)', 'onPress' is an instance of Object)
. Although I have experience with using functions as props and updating states in React, I seem to be struggling with this problem in React Native, and so far, online resources haven't provided a clear solution.

Child component:

import * as React from 'react';
import {Avatar, Button, Card, Title, Paragraph } from 'react-native-paper';

const Photo:React.FC<{url:string, camera:string, handleClick:()=>void}> = ({url, camera}:{url:string, camera:string}, handleClick:()=>void) => (
  <Card >
    <Card.Content >
      <Paragraph style={{color:'#6200ee'}}>{camera}</Paragraph>
    </Card.Content>
    <Card.Cover source={{ uri: url }} />
    <Card.Actions>
      <Button onPress={handleClick} mode='contained'>more</Button>
    </Card.Actions>
  </Card>
);

export default Photo;

Parent Component:

 import React, {useContext, useEffect, forwardRef, useState, Ref, useImperativeHandle, useRef} from 'react'
import { View, Text, ScrollView, StyleSheet } from 'react-native'
import { ActivityIndicator} from 'react-native-paper';
import {theContext}  from '../utils/ContextPlaceholder'
import getPhotos from '../utils/getPhotos'
import Photo from './Photo'
import axios from 'axios';
import {PhotosViewV2} from './PhotosViewV2'
import ImageViewer from 'react-native-image-zoom-viewer';

interface RefObject {
    getData: () => void
  }

export const PhotosView = forwardRef((props, ref: Ref<RefObject>)=> {
    const [photos, setPhotos]=useState<any[]>([])
    const[clicked, setClicked]=useState(false)
    const context=useContext(theContext)
    const{rover, camera, year,month,day} =context
    useImperativeHandle(ref, () => ({getData}));
    async function getData() {
      const photos=await getPhotos(1,rover, camera, year,month,day)
      setPhotos(photos)
    }
    return(
        <View>
        <ScrollView>
          {photos.map(({cam, url},idx)=>{
            return <Photo handleClick={()=>setClicked(true)} camera={cam} key={idx} url={url}/>
          })}
          
        </ScrollView>
        <PhotosViewV2 clickedFromOutside={clicked} data={photos}/>
        </View>
        );
  });

Answer №1

The issue lies within this snippet of code

({url, camera}:{url:string, camera:string}, handleClick:()=>void)
. The variables url and camera are extracted from the first parameter, which is labeled as props, while handleClick is obtained from the second parameter identified as forwardRef, an object. To rectify this, it should be rewritten as follows:

({url, camera, handleClick}:{url:string, camera:string, handleClick:()=>void})

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

Troubleshooting property assignment issues within an Angular service

I have created a simple injectable service in TypeScript for Angular 4. This service is designed to fetch a JSON file from the network and store the data as an array in its property called data. Other classes can then access this data using the method getD ...

Confirm Ng2 password and verify.password

These are the codes I've been working with: <form [formGroup]="registerForm" novalidate (ngSubmit)="doRegister()"> <div class="form-group" [ngClass]="{'has-danger': registerForm.control ...

What is the reason that {a: never} is not the same as never?

Is there a reason the code {a: never} cannot be simplified to just never? I believe this change would resolve the issues mentioned below. type A = {tag: 'A', value: number} type B = {tag: 'B', value: boolean} type N = {tag: never, valu ...

Experiencing various sporadic building issues in Xcode/iOS/RN since transitioning from Intel/Big Sur to M1/Monterey

My iOS React Native project is facing build issues after transitioning from an Intel Mac running Big Sur to an M1 Mac running Monterey. These problems seem to occur randomly in different components. Occasionally, simply restarting the build without making ...

When integrating the @azure/msal-angular import into the Angular application, the screen unexpectedly goes blank,

Starting a new Angular app and everything is rendering as expected at localhost:4200 until the following change is made: @NgModule({ declarations: [ AppComponent, HeaderBannerComponent, MainContentComponent, FooterContentinfoComponent ...

How can the return type of a function that uses implicit return type resolution in Typescript be displayed using "console.log"?

When examining a function, such as the one below, my curiosity drives me to discover its return type for educational purposes. function exampleFunction(x:number){ if(x < 10){ return x; } return null } ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

Building NextJS with Typescript encountered an error while using @auth0/nextjs-auth0

I am currently facing an issue while trying to build my NextJS application using Typescript. The problem lies with the auth0/nextjs-auth0 package, causing persistent errors during installation. One specific error can be found at the following link: https: ...

RouterModule error - Property 'forRoot' is undefined

I've been working on setting up routing in Angular and encountered an issue with the error message: Cannot read property 'forRoot' of undefined Here is my app.routes.ts file: import { RouterModule, Routes } from '@angular/router&ap ...

Setting up a variable with no operation assigned to it

As I delved into the Angular utils source code, I stumbled upon this interesting line: export const NOOP: any = () => {}; It seems pretty straightforward - a variable that doesn't perform any operation. But then, within the same library, there is ...

Angular 4: Exploring the Depths of Nested HTTP Requests

I'm struggling to receive a JSON response that contains an array with every declaration, including the user and category information. I currently have a static solution, but I want to implement a dynamic approach and I'm facing difficulties makin ...

What is the best way to retrieve the text when it is no longer within its original div?

Is it possible to use Javascript to detect when text is flowing out of its containing <div>? For instance, if a text consists of 3 sentences and the last sentence is only partially displayed, can JavaScript be used to capture the entire last sentence ...

Using the as operator in TypeScript for type casting a string

function doSomething(a : any) { let b = (a as Array<any>) alert(typeof b) // displays "string" } doSomething("Hello") The alert is showing "string" instead of what I anticipated, which was something along the lines of a null value. The docu ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

Error: Unable to iterate through posts due to a TypeError in next.js

Hi there, this is my first time asking for help here. I'm working on a simple app using Next.js and ran into an issue while following a tutorial: Unhandled Runtime Error TypeError: posts.map is not a function Source pages\posts\index.tsx (1 ...

Refresh Angular page data following new routing paths

The chat box page in the image below was created using Nebular: Nebular Documentation View Chat Box Photo After clicking on one of the user names (2) from the list, the URL ID (1) changes but the corresponding data does not load. Note: I have created a m ...

Setting a maximum value for an input type date can be achieved by using the attribute max="variable value"

Having trouble setting the current date as the "max" attribute value of an input field, even though I can retrieve the value in the console. Can anyone provide guidance on how to populate the input field with the current date (i.e max="2018-08-21")? var ...

Exploring the process of importing and exporting modules in TypeScript with the help of systemjs

Is there a way to export a module using systemjs in TypeScript? I encountered the error: TS1148 cannot compile modules unless the '--module' flag is provided. Here's my code; animal.ts export class Animal { color: string; age: numb ...