I have a button with a field testID
<Button testID='someButton' onPress={someButtonClick}/>
Is there any way to programatically click a button with given testID ?
I have a button with a field testID
<Button testID='someButton' onPress={someButtonClick}/>
Is there any way to programatically click a button with given testID ?
Share Improve this question edited Dec 1, 2021 at 18:57 benomatis 5,6437 gold badges39 silver badges60 bronze badges asked Aug 16, 2018 at 9:04 Barinder GrewalBarinder Grewal 591 gold badge2 silver badges6 bronze badges 2- Can you add some code for the button that you've defined? – Pritish Vaidya Commented Aug 16, 2018 at 9:05
- Possible duplicate of React-native, render a button click dynamically – Revansiddh Commented Aug 16, 2018 at 9:06
5 Answers
Reset to default 2Here is a plete implementation of one button pressing another.
import React from "react"
import { View, Button } from 'react-native';
const someButtonClick = () => {
console.log("button was pressed");
}
export class PressButton extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
clickButton() {
this.button.props.onPress();
}
render() {
return (
<View>
<Button title="another button"
onPress={() => { this.clickButton()}}
/>
<Button title="some button" testID='someButton'
onPress={() => { someButtonClick() }}
ref={(button) => {this.button = button; }}
/>
</View>
)
}
}
Note the following
- you need a ref in order to access the button.
- onPress() is the correct method in React Native, not click()
- the event handlers are in props.
You need to create a ref.
<Button id={buttonId}
onClick={e => console.log(e.target)}
ref={(button) => { this.myButton = button; }}
// Or something like this:
ref={ponent => this.myButton = ponent}
/>
And then you can access that ref somewhere else in your code:
myFunction = () => {
this.myButton.click()
}
const uploadbtn = useRef();
I am hiding this button to press it programmatically
<Button
ref={uploadbtn}
buttonStyle={{ width: 0, height: 0, opacity: 0, display: "none" }}
onPress={pickImage}
/>
And then use a function like this to press the button
const test = () => {
uploadbtn.current.handleOnPress();
};
Try this in render code.
<div className="container" hidden >
<button onClick={this.submit} ref={(button) => { this.btn = button }} />
</div>
in function
btn = () => {
this.btn.click()
}
in else code
this.btn()
in render() function
<button type='button' onClick="{this.btnClickFunc.bind(this)}">buton</button>
and
function btnClickFunc(e){
var value = e.target.value;
}
I Hope worked for you