SCROLL TO AN ARRAY ELEMENTS BY RIGHT SIDE ON CLICK BY USEREF IN REACT

This is our UI

By clicking right and left this Button scroll will change

STEP 1 :

Create a ref element for our scroll component.

  const scrollLeftRef = useRef();

STEP2:

Create a State for updating the State of scroll

  const [scrollX, setScrollX] = useState({
side: ""
});

STEP3:

Create a function for changing state

  const handleScroll = (data) => {
setScrollX(prev => ({ ...prev, side: data.side }));
}

STEP4:

Let’s listen our changes by using useEffect()

 useEffect(() => {
if (scrollX.side === "right") {
scrollLeftRef.current.scrollLeft += 200;
} else {
scrollLeftRef.current.scrollLeft -= 200;
}
}, [scrollX]);
        <div class="slide-sample">
<div id="slideRight" onClick={() => handleScroll({ side: "left" })} className="preSlide">
<i className="fas fa-caret-square-left" />
</div>
<div ref={scrollLeftRef} class="slideouter">
<div class="slideinner srcl">
<ul>
{
categories.map((category, i) => {
return (
<li key={category.id} className={activeclass === i ? "active" : "list"} >{category.name}</li>
)
})}
</ul>
</div>
</div>
<div id="slideRight" onClick={() => handleScroll({ side: "right" })} className="nextSlide">

<i className="fas fa-caret-square-right" />
</div>

</div>
 .slide-sample{
margin: auto;
position: relative;
display: table;
}
.preSlide {
left: -31px;
position: absolute;
top: 8px;
font-size: 27px;
color: #0080cd;
}
.nextSlide {
right: -30px;
position: absolute;
top: 8px;
font-size: 27px;
color: #0080cd;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store