Sometimes, we have a long list, and then we want to locate the list to one of the items that got a change but not currently been shown in the viewport, let’s see how to do that in React.
This is a horizontal list. So as a traditional react and redux guy… I first add
ref for both the list and item, and every time when the matched item should be shown and not in the view, I will get its
offsetLeft, and dispatch an action to the store, then it will trigger the re-rendering of the list, the list will
scrollTo to that offset. It mostly works, but very unstable, I get the
componentDidmount, it seems that the list is not ready even when I retrieved it in the
Then after a while, when I revisiting this code, it occurs to me that when I already got the
ref… why bother to pass it, the item can scroll itself!
styled component, this is how I get the ref.
scrollIntoView(), and you need to call it when the DOM is ready, which means in
behavioris for how to scroll,
smoothwill be a not-instant-scroll, so the user can see it’s happening
inlineis for the final position.
Check the documentation on MDN.
Beware of the browser compatibility. But seems good to me in some cases.
Hope it helps.