react focus not firing on mousedown after change focus to another component

377 Views Asked by At

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

1

There are 1 best solutions below

1
Wesley LeMahieu On

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>