react-headroom - momentarily disable when animating scroll from another component

Viewed 21

I have have a tabs-component that becomes sticky when a user scrolls past it's scroll position on the page. When a tab is clicked it will scroll the user up or down, depending on where their current scroll position is, in relation to the related tab-content's scroll position.

Is it possible to momentarily disable/reactivate the react-headroom functionality from another component, when required?

Ideally, when scroll-up is initiated via these tabs, I wish to trigger the react-headroom hide-header functionality, if the header is already shown, or disable the show-header functionality, if the header is already hidden. Any suggestions how one would achieve this?

Thanks in advance.

1 Answers

I ended up resolving this by using useState & useRef combined the headroom disable prop, then using a setTimeout of 500 to toggle the boolean condition set in useRef ~ as the animation is based on time, not distance travelled, so you can rely on the animation to have finished in that time, which you can reset the value back to !disabled.

import { useRef, useState } from 'react';
import Headroom from 'react-headroom';

const SiteHeader = (): JSX.Element => {
    const [headroomDisabled, setHeadroomDisabled] = useState(false);
    const myRef = useRef<HTMLDivElement>(null);
    const myRef2 = useRef<HTMLDivElement>(null);

    const executeScroll = () => myRef.current?.scrollIntoView();

    const executeScrollUp = () => {
        setHeadroomDisabled(true);

        myRef2.current?.scrollIntoView();

        setTimeout(() => {
            setHeadroomDisabled(true);
        }, 500);
    };

    return (
        <>
            <Headroom disable={headroomDisabled}>
                <h2>Test header content</h2>
            </Headroom>

            <div ref={myRef2}>Element to scroll to</div>
            <button onClick={executeScroll}> Click to scroll </button>

            <div style={{ marginTop: '150vh' }}></div>

            <div ref={myRef}>Element to scroll to</div>
            <button onClick={executeScrollUp}> Click to scroll </button>
        </>
    );
};

export default SiteHeader;

I ended up taking this a step further and placing this logic in some global state, as so any component could utilise this functionality.

Would be happy to share this also, if anyone is interested

Related