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, setwillChange: '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 ownvisible,hovered,pressed,trackPropsandthumbProps. Where both show, eachvisiblesays 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 whenvisibleis true. - The thumb is the track's first child, at its start. The hook sets its
length and its
transformwithout rendering, so leave those out of its style. visibleis true where the view's style scrolls that axis and its content is longer than it.minThumbLengthis 16 by default.- The nodes are yours to reach too:
trackProps.ref.current, to animate a track say. visible,hoveredandpressedrender when they change, and scrolling does not.- Cost: none while nothing changes. A
ResizeObservertells it when the view, its children or a track change size, and itsscrollevents tell it of scrolling.