React Native How to Call Multiple Functions When Onpress Is Clicked

Call multiple functions onClick ReactJS

Wrap your two+ function calls in another function/method. Here are a couple variants of that idea:

1) Separate method

var Test = React.createClass({
onClick: function(event){
func1();
func2();
},
render: function(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});

or with ES6 classes:

class Test extends React.Component {
onClick(event) {
func1();
func2();
}
render() {
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
}

2) Inline

<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>

or ES6 equivalent:

<a href="#" onClick={() => { func1(); func2();}}>Test Link</a>

how to call multiple function one by one on single button in react native

You have to maintain a count that how many times the functions has been triggered. And using that you can choose whether which function to execute when button presses.

Note: I hope that you are using class components because you mentioned onPress event with this keyword and also function name is equal to function.

Class components
constructor(props) {
super(props);
this.state = {
triggerCount: 0
};

this.functionName = this.functionName.bind(this);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}

functionName() {
switch (this.state.triggerCount) {
case 0:
this.function1();
break;
case 1:
this.function2();
break;
case 2:
this.function3();
break;
}

this.setState({
triggerCount: (this.state.triggerCount + 1) % 3
});
}

function1() {
// Your logic for function 1
}

function2() {
// Your logic for function 2
}

function3() {
// Your logic for function 3
}

render() {
return (
...
<View>
<Icon onPress={this.functionName} name="md-camera" size={30}/>
</View>
...
)
}

or

Functional components
const [triggerCount, setTriggerCount] = useState(0);

const functionName = () => {
switch (triggerCount) {
case 0:
function1();
break;
case 1:
function2();
break;
case 2:
function3();
break;
}

setTriggerCount((triggerCount + 1) % 3);
}

const function1 = () => {
// Your logic for function 1
}

const function2 = () => {
// Your logic for function 2
}

const function3 = () => {
// Your logic for function 3
}

return (
...
<View>
<Icon onPress={functionName} name="md-camera" size={30}/>
</View>
...
);

How to call for more than one functions in onPress prop?

Function.prototype.bind() returns function rather than call one. Instead of using .bind() to pass the text to the button you could do this:

onPress={() => functionOne(text)}

In this syntax, you can call two functions like so:

onPress={() => { functionOne(text); props.onChange(value); } }


Related Topics



Leave a reply



Submit