theKashey / react-focus-lock

It is a trap! A lock for a Focus. 🔓
MIT License
1.27k stars 67 forks source link

Can't click without scroll being changed #254

Closed leads closed 1 year ago

leads commented 1 year ago

Hi please see this codesandbox example and demo.

Here I am using a Modal we have built and it uses body-scroll-lock-upgrade and react-focus-lock.

If you open the Modal then scroll down the list, try clicking the label text. It will jump you back up. You can click the checkbox directly but then trying another click elsewhere it will scroll back to that focussed item.

I made a demo without checkboxes and the same thing happens if you click in a grey box. Also a demo without the body-scroll-lock.

Hopefully this is an implementation mistake on our behalf that we have missed. Any ideas?

Thanks

denkristoffer commented 1 year ago

Use preventScroll in focusOptions: https://codesandbox.io/s/happy-pascal-ndd77z?file=/src/Modal.tsx:3109-3168

See https://github.com/theKashey/react-focus-lock/issues/162

theKashey commented 1 year ago

Root cause - you have a focusable element "above" focus lock. When you click on the "text" you are selecting this element and as it is "above" focus (or "outside") the focus will be returned to where it belongs.

The fix is simple - wrap dialog with focus-lock, not the other way around - https://codesandbox.io/s/busy-blackwell-6svn9r?file=/src/Modal.tsx

How to check: you should be able to select text with a mouse. If you cannot, then something is wrong. Focus-lock implicitly allows for focus to reside on body, but nowhere else.

leads commented 1 year ago

Awesome, thank you!