Reputation: 29
I have mapped my data into timetable and showed them date wise (30 days) in horizontal scroll. I have set current date data as active element. But when the date is far like 22nd position and the view is only bound for 5 objects, how can I show the active object data (22nd object) in the center of my screen through smooth scroll on page load? (picture reference attached)
Here is my current code:
import React, { useRef, useEffect } from "react";
const DashboardData = ({
timetable,
sahriToday,
iftarToday,
currentN,
currentD,
setCurrentD,
}) => {
const handleClick = (id) => {
setCurrentD(id);
};
const dateFunc = (dhur, id) => {
let eDate = new Date(dhur);
if (currentN.getDate() === eDate.getDate()) {
setCurrentD(id);
}
}
const myRef = useRef(currentD);
useEffect(() => {
myRef.current?.scrollIntoView ({
behavior: "smooth",
block: "end"
});
}, [currentD])
console.log(currentD);
return (
<>
<div className="mother">
{timetable.map((timetable) => (
<>
<div
className={ currentD === timetable.id ? "dayboom active" : "dayboom" }
onClick={() => handleClick(timetable.id)}
ref={myRef}
>
<h3 className="weekday">{timetable.weekday}</h3>
<h3 className="monthdate">{timetable.day}</h3>
{dateFunc(timetable.edate, timetable.id)}
</div>
</>
))}
</div>
<div className="timeToday">
<div className="sahriToday">
<div>
<h2>
Sahri <span>Time</span>
</h2>
<h3>{sahriToday[0].sahri}</h3>
</div>
</div>
<div className="iftarToday">
<div>
<h2>
Iftar <span>Time</span>
</h2>
<h3>{iftarToday[0].iftar}</h3>
</div>
</div>
</div>
</>
);
};
export default DashboardData;
I have tried scrollIntoView() but that works on the full map data, not the specific one that is active.
Upvotes: 0
Views: 267
Reputation: 241
If you don't need to save the reference for each of the elements in the map you can try adding a ref only for the element you want the function scrollIntoView do its thing. Something like:
ref={currentD === timetable.id - 2 ? myRef : null}
Upvotes: 1