Event when useRef element have height more than zero

994 views Asked by At

I have big list of photo thumbnails, and I should be able to scroll one of thumbnails into view when list is loaded.

Photos are populated with map function, and one of the thumbnails' container div will be given ref.

I tried useEffect:

useEffect(() => {
    if (scrollRef.current && scrollRef.current instanceof HTMLDivElement) {
        scrollRef.current.scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'center',
        });
    }
}, [scrollRef.current]);

Problem is that ref or ref.current cannot be used as dependency list of useEffect. I get warning:

React Hook useEffect has an unnecessary dependency: 'scrollRef.current'. Either exclude it or remove the dependency array. Mutable values like 'scrollRef.current' aren't valid dependencies because mutating them doesn't re-render the component

How can I fire useEffect or some other function when ref.current changes? And by changes, I mean specifically its clientHeight value changes. Because initially it is zero, and scrollIntoView does not work yet.

1

There are 1 answers

0
f1nan On

Use a callback ref.

function Example() {
    const [divRef, setDivRef] = useState(null);

    useEffect(() => {
        if (divRef && divRef.clientHeight > 0) {
            div.scrollIntoView({
                behavior: 'auto',
                block: 'center',
                inline: 'center',
            });
        }
    }, [divRef]);

    return <div ref={setDivRef} />;
}