'React check if element has inner scroll

useEffect(() => {
    if (middleRef.current.scrollHeight) {
        console.log(
            middleRef.current.scrollHeight > middleRef.current.clientHeight,
            'loggie'
        );
        let scrollableCheck =
            middleRef.current.scrollHeight > middleRef.current.clientHeight;
        setScrollable(scrollableCheck);
    } else {
        console.log('else');
    }
}, [middleRef.current.scrollHeight]);

With this code I'm trying to find out if the element has a scrollbar or not. I think the problem is that when it checks the HTML element isn't rendered yet. I tried all sorts of other examples but nothing seems to work. This code doesn't crash the page but also doesn't do what is should

Some other code I tried:

Uncaught TypeError: Cannot read properties of null (reading 'scrollHeight')

useEffect(() => {
    let middleId = document.getElementById('middle');
    checkForScrollBar(middleId);
}, []);

function checkForScrollBar(middleId) {
    let scrollableCheck = middleId.scrollHeight > middleId.clientHeight;
    setScrollable(scrollableCheck);
}

_

useEffect(() => {
    let scrollableCheck = middleId?.scrollHeight > middleId?.clientHeight;
    setScrollable(scrollableCheck);
}, [middleId.clientHeight]);

It should be a pretty simple thing to check for but I'm a bit lost with what I'm doing wrong.



Solution 1:[1]

In your first code block, line 2, inside if statement, you should write middleRef.current.scrollHeight not middleRef.scrollHeight.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehdi Namvar