1

https://react-ts-m8xqqr.stackblitz.io

https://stackblitz.com/edit/react-ts-m8xqqr?file=App.tsx

sandbox to follow

I have a table and button components When page is loaded initially mousedown on table results focusing on the cell - as expected Then button is clicked Without reloading the page, mousedown on table not resulting focus on the cell - not as expected? Then any key pressed, focus is visible on the cell with the latest mousedown cell

I am trying to understand what is causing this behaviour, especially after clicking on button why mousedown not working as previously on table?

expected: following the button click, when table is clicked focus should be gained

actual: following the button click, when table is clicked focus is lost, and only appears after any key is pressed

bilet
  • 11
  • 2

1 Answers1

0

The reason your cells lose focus when you click your button is because you're not using a reference on the button for focus. Once you switch from React focus to non-React focus is when the break happens.

Simply use this to prevent the non-React focus from occurring:

On your <button> element add:

onMouseDown={(e) => e.preventDefault()}

So now it should look like:

<button
  onMouseDown={(e) => e.preventDefault()} {/* <--- add this line */} 
  onClick={() => setCount((prev) => prev + 1)}
>
  {' '}
  Count: {count}
</button>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Wesley LeMahieu
  • 2,296
  • 1
  • 12
  • 8
  • Thank you @Wesley, while it works when (pd) preventdefault is added, I was hesitant to follow that route and add pd to all components mouse down is not handled explicitly. Could you please elaborate more on the difference between react/non-react focus? how is it relevant to keydown event? I am asking because without pd keydown is gaining focus while mousedown didn't. – bilet Feb 12 '23 at 19:04