reactjsreact-nativeonpressundefined-function

Undefined is not a function - react-native onPress


undefined is not a function error that points to this line in my code:

onPress={() => handleCardPress(item)}

I'm following along with this tutorial: React-Native App

I tried adding this to test if anything changed but I got the same error:

const handleCardPress = (item) => {
  // Function logic to handle the card press event
  console.log('Card pressed!', item);
};

Here is my PopularJobCard.jsx:

import { View, Text, TouchableOpacity, Image } from 'react-native'

import styles from './popularjobcard.style'

import { checkImageURL } from '../../../../utils'


const PopularJobCard = ({ item, selectedJob, handleCardPress}) => {
  return (
    <TouchableOpacity
      style={styles.container(selectedJob, item)}
      // onPress handleCardPress on item
      onPress={() => handleCardPress(item)}
    >
      <TouchableOpacity style={styles.logoContainer(selectedJob, item)}>
        <Image
        source={{ uri: checkImageURL(item?.employer_logo)
              ? item.employer_logo
              : "https://t4.ftcdn.net/jpg/05/05/61/73/360_F_505617309_NN1CW7diNmGXJfMicpY9eXHKV4sqzO5H.jpg",
          }}
          resizeMode="contain"
          style={styles.logoImage}/>
      </TouchableOpacity>
      <Text style={styles.companyName} numberOfLines={1}>{item.employer_name}</Text>
      <View style={styles.infoContainer}>
        <Text style={styles.jobName(selectedJob, item)} numberOfLines={1}>{item.job_title}
        </Text>
        <Text style={styles.location}>{item.job_country}</Text>
      </View>

    </TouchableOpacity>
  )
}

export default PopularJobCard

When I press on the job card I get the following error error


Solution

  • You need to provide a function as handleCardPress to PopularJobCard like it's a prop. There's an example of this in the repo you've shared: https://github.com/adrianhajdin/project_react_native_jobs/blob/main/components/home/popular/Popularjobs.jsx#L51

    In the example, they define a function 'handleCardPress' and pass it to the component where it's used. This way PopularJobCard is flexible to accept different functions.