Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React prevent onClick firing when onFocus fires

My field onClick event toggles a dropdown, the onFocus event opens it.
When the onFocus event is fired the onClick event is fired afterwards and closes the newly opened dropdown. How can I prevent firing on Click in Case onFocus fired?

preventDefault and stopPropagation do not work, both events are always fired

<TextInputV2
  label={label}
  onChange={handleInputOnChange}
  onClick={handleOnClick}
  onFocus={handleOnFocus}
  onKeyUp={handleInputOnKeyUp}
  readOnly={!searchable}
  value={inputValue}
/>

.......

  const handleOnFocus = (event: React.FocusEvent): void => {
    if (!isOpen) {
      changeIsOpen(true)
    }
  }

  const handleOnClick = (event: React.SyntheticEvent): void => {
    if (!searchable) {
      toggleOpen()
    }
  }
like image 450
jeff Avatar asked Dec 31 '22 16:12

jeff


1 Answers

You will want to change onClick to onMouseDown. Since event order is

  • mousedown
  • change (on focused input)
  • blur (on focused element)
  • focus
  • mouseup
  • click
  • dblclick

from: this answer

You want to preventDefault/stoPropagation BEFORE the focus event, which means you have to use "onMouseDown" to properly stop it before the focus event get triggered.

In your case it would be:

<TextInputV2
  label={label}
  onChange={handleInputOnChange}
  onMouseDown={handleOnClick}
  onFocus={handleOnFocus}
  onKeyUp={handleInputOnKeyUp}
  readOnly={!searchable}
  value={inputValue}
/>
 const handleOnClick = (event) => {
    event.preventDefault()
    event.stopPropagation()
  if (!searchable) {
   toggleOpen()
  }
}
like image 146
JCQuintas Avatar answered Jan 08 '23 01:01

JCQuintas