react native how to call multiple functions when onPress is clicked

Viewed 61723

I am trying to call multiple functions when I click onPress using TouchableOpacity

For example:

functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableHighlight onPress{() => this.functionOne()}/>

What if I want to call two functions when onPress is clicked? Is there a way I could call multiple functions?

10 Answers

There are a few ways to achieve this. One option would be to define a function that calls functionOne and functionTwo, and pass that on your onPress handler like so:


functionOne(){
// do something
}

functionTwo(){
// do something
}

functionCombined() {
    this.functionOne();
    this.functionTwo();
}  

<TouchableHighlight onPress={() => this.functionCombined()}/>

Alternatively, and more concisely, you could express functionCombined inline in your JSX like so:


functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableHighlight
 onPress={
  () => { this.functionOne(); this.functionTwo(); }
 }
/> 

      

Recommended Solution:

   <TouchableWithoutFeedback
    onPress={() => {
     function1();
     function2();
    }}>     

You can use these props:

onPress Called when the touch is released

onPressIn Called as soon as the touchable element is pressed and invoked before onPress.

<TouchableWithoutFeedback
    onPress={() => {
      function1();
    }}
    onPressIn={() => {
      function2();
    }}
 >
 

If you want to call a function and then navigate to a screen, then do this way.

<TouchableOpacity onPress={() => { this.onSubmit(); this.props.navigation.navigate('NextScreen') }}>

You can also make this with a boolean value. Example ;

<TouchableHighlight onPress{() => { this.functionOne() || this.functionTwo()}}/>

Seeking your comment, you want to not used arrow, so I'm suggest to use something like this:

functionOne(){
// do something
}

functionTwo(){
// do someting
}

mixFunction=()=>{
functionOne();
functionTwo();
}

mixFuncWithoutArrow(){
functionOne();
functionTwo();
}

<TouchableHighlight onPress{this.mixFunction() || this.mixFuncWithoutArrow.bind(this)}/>

This is an example and it works (from ELYES)

onPress={() => {
    setIsOpen(true);
    setTimeout(
        () =>  props.navigation.navigate("Login"),
        1000
    );
}}  

I think it is simple, we use just PLUS '+' between the functions :

<TouchableHighlight onPress = {() => this.functionOne() + this.functionTwo() } />

We can also call the second method from this first one, like this way....

functionOne(){
 // do something
 functionTwo();
}

functionTwo(){
 // do someting
}

<TouchableHighlight onPress{() => this.functionOne()}/>

This should work

<TouchableOpacity
    onPress={() => {
      functionA();
    }}
    onPressIn={() => {
      functionB();
    }}>
 </TouchableOpacity>
<Button 
onPress={() =>{
onIncrease();
show();
}}
 title={`Increase ${color}`}
/>`enter code here`
Related