Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onPress in functional react native component not working

I'm trying to create a simple reusable button component in react-native but for some reason the onPress function never gets called. Most threads I find simply call the function instantly or declared something wrong I believe everything should be fine with my declaration and I tried several different forms as well but to no avail

import React from 'react';
import { Text, Button, Image, TouchableOpacity } from 'react-native';
import { useHistory } from "react-router-native";
import { getFileUrl } from '../db/firebaseDb';
import styles from '../modules/Styles';

const GameIcon = (props) => {
  const history = useHistory();

  const handleClick = (pId) => {
    console.log("TEST");
    history.push("/game");
  }

  return (
    <TouchableOpacity activeOpacity="0.5" onPress={handleClick}>
      {(props.imageUrl)?<Image source={{uri: props.imageUrl}} style={{width: 32, height: 32}}/>:<Text>loading...</Text>}
      <Button title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}/>
    </TouchableOpacity>
  )
}

export default GameIcon;

The console.log is never triggered and I have no clue why ... I tried writing the component as function GameIcon ... I tried this without the TouchableOpacity and just having the button in the return function ... nothing works neither on an actual device nor an emulator

Small update:

I changed the content of the return function to:

<TouchableOpacity activeOpacity={0.5} onPress={()=>console.log("HELLO")}>
  <Text title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}>{props.game.id}</Text>
</TouchableOpacity>

The component renders with no errors or anything, it can be tabbed and the opacity changes correctly but onPress is not called (so no console log)

This doesn't seem to be limited to only functional components ...

I added the button example from the react-native docs 1:1 onto my homescreen and the onPress event never gets called:

<Button
  onPress={() => {
    alert('You tapped the button!');
  }}
  title="Press Me"
/>
like image 780
Dinkelborg Avatar asked Oct 20 '25 03:10

Dinkelborg


1 Answers

Please try this code.

import React from 'react';
import { Text, Button, Image, TouchableOpacity } from 'react-native';
import { useHistory } from "react-router-native";
import { getFileUrl } from '../db/firebaseDb';
import styles from '../modules/Styles';

const GameIcon = (props) => {
  const history = useHistory();

  const handleClick = (pId) => {
    console.log("TEST");
    history.push("/game");
  }

  return (
    <TouchableOpacity activeOpacity={0.5} onPress={handleClick}>
    <Text title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}>{props.game.id}</Text>
    </TouchableOpacity>
  )
}

export default GameIcon;
like image 169
gypsicoder Avatar answered Oct 21 '25 17:10

gypsicoder