How to programmatically trigger click event in React?
You could use the ref prop to acquire a reference to the underlying HTMLInputElement
object through a callback, store
the reference as a class property, then use that reference to later trigger a click from your event handlers using the
HTMLElement.click
method.
This can be done in two steps:
-
Create ref in render method:
import React from 'react'const InputComponent = () => {const inputElement = React.useRef()return <input ref={inputElement} />} -
Apply click event in your event handler:
inputElement.click() -
Other possible event you can call:
inputElement.focus()inputElement.blur()
November 06, 2022
48572
Read more
What is React?
November 06, 2022
ReactJS