I have a react component that displays a list of images horizontally across the page.
I would like to be able to scroll horizontally through them without having to hold in the SHIFT button.
Is there a way I change the default for just this component using css or react?
Here is my code: https://codesandbox.io/s/team-grid-slicer-2db8d
CodePudding user response:
You can create a ref
and bind it to your div
which you will scroll. Here is a working codesandbox
Basically you create a ref and assign it to the div
const scrollRef = useRef()
...
<div ref={scrollRef}>
And you listen to the changes on the wheel
event within the div:
if(scrollRef.current){
scrollRef.addEventListener('wheel', /* your function */)
}
And you scroll to left, instead of down based on the wheel event's deltaY:
el.scrollTo({
left: el.scrollLeft e.deltaY * 5,
behavior: "smooth"
});
PS: You can remove * 5
but it looks better imo
CodePudding user response:
just add an id="container
to your component and then add
onWheel={(e) => {
e.preventDefault()
var container = document.getElementById('container')
var containerScrollPosition = document.getElementById('container').scrollLeft
container.scrollTo({
top: 0,
left: containerScrollPosition e.deltaY,
behaviour: 'smooth' //if you want smooth scrolling
})
}}
This will listen to the onWheel and scroll your component.