Soundor

useScrollbar

A scrollbar of your own, drawn however you like.

useScrollbar gives tracks and thumbs of your own what scrollbars do: a thumb shows what is in view and drags, and a press on its track jumps there. They are ordinary nodes, so they look like whatever you draw, wherever you put them, in every runtime. They scroll any view whose style scrolls: a View or Animated.View with overflow: 'scroll' (or overflowX/overflowY).

Safari and iOS WebKit. WebKit can paint scrolling content over a custom scrollbar even when the track has a higher zIndex. For a track that overlays the content, set willChange: 'transform' on the track's style, as shown below.

const list = useRef<UiNode>(null);
const { vertical } = useScrollbar(list);

return (
  <View style={{ flex: 1 }}>
    <View
      ref={list}
      scrollIndicators={false}
      style={{ flex: 1, overflowY: 'scroll' }}
    >
      {children}
    </View>
    {vertical.visible && (
      <View
        {...vertical.trackProps}
        style={{
          position: 'absolute',
          top: 2,
          bottom: 2,
          right: 2,
          width: 8,
          zIndex: 1,
          willChange: 'transform',
        }}
      >
        <View
          {...vertical.thumbProps}
          style={[styles.thumb, vertical.pressed && styles.thumbPressed]}
        />
      </View>
    )}
  </View>
);
  • Both axes: it returns { vertical, horizontal }, a bar for each; draw the ones you need. Each has its own visible, hovered, pressed, trackProps and thumbProps. Where both show, each visible says whether to leave the corner to the other.
  • Where they go: render each track as a sibling of the scrolling view so it stays in place. For an overlay, position the track absolutely and set zIndex: 1. You can also give tracks their own room in a row. To keep that room when there is nothing to scroll, render the track always and only show the thumb when visible is true.
  • The thumb is the track's first child, at its start. The hook sets its length and its transform without rendering, so leave those out of its style.
  • visible is true where the view's style scrolls that axis and its content is longer than it. minThumbLength is 16 by default.
  • The nodes are yours to reach too: trackProps.ref.current, to animate a track say.
  • visible, hovered and pressed render when they change, and scrolling does not.
  • Cost: none while nothing changes. A ResizeObserver tells it when the view, its children or a track change size, and its scroll events tell it of scrolling.