Joey Yi Zhao
Joey Yi Zhao

Reputation: 42474

How to manually trigger a click event on a dom in reactjs

I want to manually trigger a onclick event on a input element. I did some search and wrote the code as below.

<input type="date" ref={datePicker => this.datePicker = datePicker}/>
            <button
                    onClick={(e) => {
                      this.datePicker.click()
                    }}>
             Select the data
            </button>

Then I also tried below code:

<input type="date" ref='datePicker'/>
                <button
                        onClick={(e) => {
                          this.refs.datePicker.click()
                        }}>
                 Select the data
                </button>

None of above code works. When I click the button , nothing happens. I expect to open the data picker ui.

Upvotes: 1

Views: 6693

Answers (2)

Codebling
Codebling

Reputation: 11382

I tried both your examples, and the <input> element's .click() method is indeed called. The reason it's not working as you expect is that it the click only puts the keyboard focus in the element, it does not click the date picker. Opening the date picker programmatically is currently not possible, at least not in all browsers.

Upvotes: 1

Vinnie James
Vinnie James

Reputation: 6042

Try without calling it as a function:

onClick={(e) => {this.datePicker.click}}>

Upvotes: 0

Related Questions