rommguy / react-custom-scroll

Easily customize the browser scroll bar with native OS scroll behavior
MIT License
555 stars 66 forks source link
css javascript reactjs

NPM version

React-Custom-Scroll

An easily designable, cross browser (!!), custom scroll with ReactJS.

The actual scroll is still the native one - Meaning the scroll animations and scroll rate work as always The only thin that is different is the visible design and scrollbar layout.

See a working demo

Installation

npm i react-custom-scroll --save

Why do I need this ?

How to use ?

Custom scroll component is available in module or commonJS format.
It is located in /dist directory
From unpkg cdn:

Wrap your content with the custom scroll component
Remove any overflow style properties from your content root component - The custom scroll will take care of it

import { CustomScroll } from "react-custom-scroll";
<CustomScroll>
  your content
</CustomScroll>

How to change the design ?

Your own custom design can be applied by styling these 2 classes in your css:

You can see a usage example in the demo page.

Options (react props)

Example for heightRelativeToParent
<CustomScroll heightRelativeToParent="calc(100% - 20px)">
  your content
</CustomScroll>  

It doesn't work, please help me

Typescript

Usage with flexbox

See a demo with Flex

There are some details that apply when using customScroll on elements with size set by css flex.
Here is an example for an HTML structure before using customScroll:

<SomeParent style="display: flex; height: 500px;">
  <FixedHeightElement style="height: 100px"><FixedHeightElement />
  <FlexibleHeightElement style="flex:1; overflow:scroll">
    your content (with enough height to cause a scroll)
  <FlexibleHeightElement />
</SomeParent>  

In this example, a scroll is active on the flexibleHeightElement, where the flex size sets it's height to 400px, after the fixedHeight element took 100px.

Solutions

There are 2 options to use customScroll with this structure:

<someParent style="display: flex; height: 500px;">
  <fixedHeightElement style="height: 100px"><fixedHeightElement/>
  <flexibleHeightElement style="flex:1; min-height: 0; min-width: 0">
    <CustomScroll heightRelativeToParent="100%">
      your content (with enough height to cause a scroll)
    <CustomScroll/>
  <flexibleHeightElement/>
</someParent>  

min-height and min-width are required since flex won't shrink below it's minimum content size (flex box spec).

<someParent style="display: flex; height: 500px;">
  <fixedHeightElement style="height: 100px"><fixedHeightElement/>
  <CustomScroll flex="1">
      your content (with enough height to cause a scroll)
  <CustomScroll/>
</someParent>  

Contributing

This project is built using Vite. To run in dev mode - "yarn dev" or "npm run dev". To build the project - "yarn build" or "npm run build".

Tests

npm install
npm test
# Or for continuous run
npx karma start