SCROLL TO AN ARRAY ELEMENTS BY RIGHT SIDE ON CLICK BY USEREF IN REACT
2 min readNov 24, 2022
HEY HEY,
This is Azim , I got a peculiar horizontal scrollbar by clicking Button in React JS.
I am writing this so that at least one person will get help from this.
This is our UI
So,
I assume you that you are proficient in React.
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]);
THAT’S IT
<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>
Here are CSS Files
.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;
}
HOPE you will get this better OUTPUT from this.