Call function onPress React Native

Viewed 50129

I just want to know how to call a function onPress. I've setup my code like this:

export default class Tab3 extends Component {
    constructor(props) {
        super(props);
        this.state = {myColor: "green"};
    }

    handleClick = () => {
        if (this.state.color === 'green'){
           this.setState({myColor: 'blue'});
        } else {
           this.setState({myColor: 'green'});
        }
    }

    render() {
     return(
      <View>
           <Icon
            name='heart'
            color={this.state.myColor}
            size= {45}
            style={{marginLeft:40}}
            onPress={() => handleClick(this)}                                 
            />
      </View>
      )};

But when I try this, I'm getting error that can't find variable handleClick

Please help. I just want to know how to bind a function to a click event.

5 Answers

A little late to the party, but just wanted to leave this here if someone needs it

export default class mainScreen extends Component {

handleClick = () => {
 //some code
}

render() {
 return(
  <View>
       <Button
        name='someButton'
        onPress={() => {
            this.handleClick(); //usual call like vanilla javascript, but uses this operator
         }}                                 
        />
  </View>
  )};

you can also try this way of binding

this.handleClick = this.handleClick.bind(this) 

and put this inside constructor. And while calling use this syntax

onPress = {this.handleClick}

This will surely solve your problem.

If you are not using class components, you can just drop the this

This function can handle the navigation for any route (as long as there is one screen with the name passed as the argument) removing the need for multiple handlers.

const navigation = useNavigation(); 

function handleNavigation(route) {
    navigation.navigate(route);
}

and the button will look like this:

<Button onPress={() => handleNavigation("Menu")} ></Button>
Related