Skip to content

Instantly share code, notes, and snippets.

@vogelino
Created April 6, 2022 15:53
Show Gist options
  • Save vogelino/d4af7f5954053dbc6b58a59fa59c92a7 to your computer and use it in GitHub Desktop.
Save vogelino/d4af7f5954053dbc6b58a59fa59c92a7 to your computer and use it in GitHub Desktop.
React Hook: Get Scrollbar Width

React Hook: Get Scrollbar Width

Code by Robin Wieruch copied from his article

import * as React from 'react';
export const useScrollbarWidth = () => {
const didCompute = React.useRef(false);
const widthRef = React.useRef(0);
if (didCompute.current) return widthRef.current;
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
didCompute.current = true;
widthRef.current = scrollbarWidth;
return scrollbarWidth;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment