Lieke
Lieke

Reputation: 51

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.

Upvotes: 1

Views: 5104

Answers (1)

Mehdi Namvar
Mehdi Namvar

Reputation: 1151

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

Upvotes: 2

Related Questions