mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
93.37k stars 32.14k forks source link

[FocusTrap] Option to `preventScroll` when focusing #36508

Open serhanguney opened 1 year ago

serhanguney commented 1 year ago

Duplicates

Latest version

Summary 💡

The FocusTrap component should be able to focus without scrolling to the selected element. The default behavior could be set to scroll to the element, and the user can optionally choose to preventScroll={true}.

Examples 🌈

Here is a specific case where FocusTrap scrolls to an element outside the viewport and triggers a layout shift creating a non-actionable white space at the bottom of the page. Note that body has overflow: hidden, and the element which is being scrolled to has position: absolute.

https://codesandbox.io/s/joyride-qwed1r?file=/src/App.tsx

Motivation 🔦

In the example I gave I tried to replicate a specific case where I'm using react-joyride to go through the steps of a tutorial. In such cases the positioning can be dynamic: For example, I have a dynamically created list of elements and I'm rendering the Popper at the very bottom of that list which can sometimes overflow the window. My guess is that since react-joyride uses a portal-like approach the scroll event triggered by default when we focus causes a layout shift as it has position absolute against html or document. In such circumstances (especially for smaller screens) it might be valuable to provide the option to preventFocus

element.focus({
 preventFocus:true
})
hbjORbj commented 1 year ago

I added a "waiting for upvotes" label. Let's wait to hear other community members' opinions!