Simple react component to enable scrolling with the mouse.
yarn add drag-scroll-provider
or
npm install --save drag-scroll-provider
import DragScrollProvider from 'drag-scroll-provider'
<DragScrollProvider>
{({ onMouseDown, ref }) => (
<div className="scrollable" ref={ref} onMouseDown={onMouseDown}>
// content that overflows the parent
</div>
)}
</DragScrollProvider>
.scrollable {
width: 500px;
overflow-x: scroll;
}
optional: hide the scrollbar
.scrollable::-webkit-scrollbar {
display: none;
}
<DragScrollProvider
vertical='true' // for vertical scrolling
threshold={0.015} // threshold in seconds for handling click and drags in clickItem function
/>
{{
onMouseDown: function, // required
ref: React ref, // required
clickItem: function, // wraps onClick events on children
scrollTo: function, // scroll to specific value (useful for animations),
}}
When you need to handle a click events on child components you need to wrap your click event on this provided function so the scroller knows that is not a drag triggering click, mainly for avoiding weird issues with the scroll.
Lets say you have a <Card />
component that handles a click event
<Card onClick={this.handleClick}>
So we need to wrap this click event like this
<DragScrollProvider>
{({ onMouseDown, ref, clickItem }) => (
<div
className="example__scroll"
ref={ref}
onMouseDown={onMouseDown}
>
<Card onClick={() => clickItem(this.handleClick)}>
</div>
)}
</DragScrollProvider>