I’m making a website with react typescript and tailwind and in it, there is a vertical list of the days of the month. The idea is that when you click on a day, it scrolls to the visible part of the div, that is 24rem under the top.
I have this function to scroll the selected day to the top of the page, but I actually need it to scroll 24rem below the top
useEffect(() => {
// Scroll to the selected day when the component mounts or when the selected date changes
if (scrollRef.current) {
const selectedDayElement = scrollRef.current.querySelector(".selected-day");
if (selectedDayElement) {
selectedDayElement.scrollIntoView({
behavior: "smooth",
block: "start",
});
scrollRef.current.scrollTop;
}
}
}, [value]);
I tried ‘block: "center"’ and ‘nearest’ but I need a more specific position. Chat GPT suggested some things using an offset property but none of them seemed to have any effects.
2
Answers
I found something on the CSS that solved my problem. I'm using tailwind CSS so what worked for me was using "scroll-mt-[24rem]" on the element that's being scrolled. In pure CSS it would be "scroll-margin-top: 24rem. This makes the scroll function consider the margin, with the defined value.
No need to use refs here.
Just use
window.scrollTo(0, 24rem)
inside the effect hook.