Home > OS >  Set focus on element after clicking 'scroll to top' button
Set focus on element after clicking 'scroll to top' button

Time:12-01

I have a ScrollToTop component, which essentially scrolls to the top after clicking on the button however I've noticed that the focus stays on the button. How would I go about setting the focus to an element in another component?

Here's my ScrollToTop component:

const ScrollToTop = () => {
    const [showScrollButton, setShowScrollButton] = useState<boolean>(false)

    const checkScrollToTop = () => {
        if (!showScrollButton && window.pageYOffset > 400) {
            setShowScrollButton(true)
        } else if (showScrollButton && window.pageYOffset <= 400) {
            setShowScrollButton(false)
        }
    };

    const scrollToTop = () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    window.addEventListener('scroll', checkScrollToTop)

    return (
        <button
            type='button'
            onClick={scrollToTop}
        >
        </button>
    );
}

export default ScrollToTop;

And then I simply import it into the page, however the element I want the focus to be set on is within the List component:

return (
  <div>
    <List collections={collections} />
  </div>
  <ScrollToTop />
);

CodePudding user response:

document.getElementById("yourElementID").focus();

The above line focuses the element with ID yourElementID.

Try adding that line after scrolling.

Change

 const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
 };

To

const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    document.getElementById("yourElementID").focus();
};

CodePudding user response:

In your case, the ScrollToTop component changes the behaviour of the List component. Therefore I would extract the handling for this into the parent component, which is rendering both components.

I created a small demo (with some irrelevant typescript errors), which shows more clearly what I mean: https://codesandbox.io/s/scrolltotopdemo-dh3q3

Basically:

  1. Make a state in the "Parent component", which controls the focus of the List component
  2. Use a react ref to set the focus to the input element https://reactjs.org/docs/hooks-reference.html#useref
  3. Call a function in the ScrollToTop component when the button is clicked.
  • Related