So I have a component that have a fixed width with an overflow-x-auto. I decided to hide the scroll bar and replace it with 2 arrow/button both left and right. If I click left, it scroll to left and vice versa. How can I achieve this functionality ?
this is my component
<div className={` vertical-card w-7/12 flex flex-row overflow-x-scroll no-scrollbar pb-4`}>
{
dataConselor.map((item, index) => {
return <VerticalCard key={item.id} name={item.nama} specialist={item.specialist} shortdesc={item.shortdesc} img={item.img} />
})
}
</div>
CodePudding user response:
- Target the scrollable element (you can use useRef, since it's react):
const scrollable = useRef(null);
<div id="myElement" ref={scrollable}>
...
</div>
- Create the scroll function:
const scrollIt = (toRight) => {
const scrollLength = ... //Calculate your scroll length however you want.
scrollable.current.scrollBy({left: scrollLength * (toRight ? 1 : -1), behavior: "smooth"});
}
- Add this function to the left/right buttons:
<div id="toLeft" onClick={()=>scrollIt(false)}>...</div>
<div id="toRight" onClick={()=>scrollIt(true)}>...</div>
CodePudding user response:
As you are using tailwind css, you can use a tailwind carousal component to achieve this behaviour.
There are various carousals available over here.