0

So I was reading the solution here: https://stackoverflow.com/Questions/4814398/how-can-i-check-if-a-scrollbar-is-visible

This is what I am going with...

function hasScrollbar() {
    console.log(
        "hasScrollbar:",
        document.body.scrollHeight > document.body.clientHeight
    );
    return document.body.scrollHeight > document.body.clientHeight;
}
<div
    className="landing-top"
    style={{ paddingRight: hasScrollbar() ? "0px" : `${scrollBarWidth}px` }}
></div>

However, because of reacts virtual dom, it doesn't seem to be reading it correctly...

enter image description here

Does anyone have any ideas?

Amila Senadheera
  • 8,033
  • 10
  • 17
  • 34
Fiddle Freak
  • 1,566
  • 2
  • 29
  • 68

2 Answers2

0

You can try using

const overflows = document.body.scrollHeight > document.body.clientHeight;

Akmal
  • 119
  • 1
  • 5
0

For some unknown reason this didn't work when I tried it before, but it is working now...

const [isScrollBarVisible, setIsScrollBarVisible] = useState(false);
function hasScrollbar() {
  return document.body.scrollHeight > document.body.clientHeight;
}
useEffect(() => {
  setIsScrollBarVisible(hasScrollbar());
}, [isLoadingData, isSearchingData, searchText]);
<div
  className="landing-top"
  style={{ paddingRight: isScrollBarVisible ? '0px' : `${scrollBarWidth}px` }}
>...more html elements here...</div>

I think all I ended up doing to fix it was restarting the server. Very weird, but this is working now.

Fiddle Freak
  • 1,566
  • 2
  • 29
  • 68