Home > Software engineering >  Doubleclick in React
Doubleclick in React

Time:03-24

I created a div which contains an input component and set pointer-events to none. I wrote the code in such a way that when the user clicks anywhere in the div, the input gets the focus by using ref's. Now the problem is that when I double click on the typed text, instead of selecting the text the focus event is triggered and the cursor appears at the end of the text instead of selecting it. How can I revert back to the default behaviour?

<div className="flex relative" onClick={() => inputRef.current.focus()}>
    <input className="pointer-events-none" type='text' ref={inputRef} />
</div>

CodePudding user response:

You can check if the current clicked element is your input or not. If it is, you can ignore the focus logic

<div className="flex relative" onClick={(e) => {
   //if your current clicked element is not the input, it will execute `focus`
   if(e.target !== inputRef.current) { 
      inputRef.current.focus() 
   }
}}>
    <input className="pointer-events-none" type='text' ref={inputRef} />
</div>
  • Related