3

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 ?

2

5 Answers 5

2

Here is a complete 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.
Sign up to request clarification or add additional context in comments.

Comments

1

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={component => this.myButton = component} /> 

And then you can access that ref somewhere else in your code:

myFunction = () => { this.myButton.click() } 

2 Comments

If I have multiple buttons with different "testID"s , how can I use this code to click a button with given "testID" ?
You put different refs on different buttons. so ref={component => this.myButton1 = component} and ref={component => this.myButton2 = component} and so on.
1
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(); }; 

Comments

-1

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() 

1 Comment

Question says "React Native"
-3

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

2 Comments

This is not at all what he is asking for.
I am asking different question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.