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>
);
});