Answer the question
In order to leave comments, you need to log in
How to find out if the scroll is scrolled to the desired element?
In general, it is necessary that the menu item be highlighted when scrolling, depending on the location of the scroll, the main difficulty is that there is a large nesting and it is not possible to check components through ref , since it is rather problematic to scroll it from a child component, and then two more levels lower it is necessary to lower it, and as far as I know it is a bad practice through IDs.
So I wanted to know if there are any ways or just these?
Now the working code looks something like this, the react-router-hash-link library is also used here , so if the component is in the view area, then I push the necessary hash as an anchor so that it applies the active class to the link itself
const scrollHandler = useCallback(() => {
const MFE_Content: HTMLElement | null = document.getElementById("MFE_Content");
const StudyFAQ: HTMLElement | null = document.getElementById("studyFAQ");
const AskQuestion: HTMLElement | null = document.getElementById("askAquestion");
if (StudyFAQ && isInViewport(StudyFAQ)) {
history.push(EnrollmentPortalHomeAnchorRoutes.HOME_STUDY_FAQ);
} else if (AskQuestion && isInViewport(AskQuestion)) {
history.push(EnrollmentPortalHomeAnchorRoutes.HOME_ASK_A_QUESTION);
} else if (MFE_Content && isInViewport(MFE_Content)) {
history.push(EnrollmentPortalHomeAnchorRoutes.HOME_ANCHOR);
}
}, [history]);
function isInViewport(el: HTMLElement): boolean {
const rect = el.getBoundingClientRect();
const elemTop = rect.top;
const elemBottom = rect.bottom;
const elemCenter = ((elemTop + elemBottom) / 2);
return (elemTop >= 0) && (elemCenter <= window.innerHeight);
}
<NavHashLink
smooth
className="nav-link"
to={'/home/#askAquestion'}
scroll={el => scrollWidthOffset(el)}>Ask a question</NavHashLink>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question