react-custom-scrollbars
react-custom-scrollbars copied to clipboard
Manual scroll top reset is not working
I was trying to reset scroll top value to "0" on every time whenever it gets updated (with some condition). I called the method scrollToTop() but its not being set to '0'.
Scenario: Tried searching something using auto-suggest which is using custom scrollbar , So when we search a result and scroll the result to an extent and then searching for a new result make the scroll bar position persist in the same location.
The result i'm looking for is that on each search the scroll should reset.
I do this like so:
<Scrollbars
ref={ (scrollbar) => { this.scrollbar = scrollbar; } }
>
Content
</Scrollbars>
And then when you want to scroll to top, call the method:
componentDidUpdate = () => {
this.scrollbar.scrollToTop();
}
@knightjdr This works fine but when I change any value into my form where the scrollbar component is present then it is taking it to top position everytime I just need to get to top position whenever my form is rendered. Anyways thanks for the solution!
@sridhar37 My solution was specific to the question where he wants to reset the scroll position on every update. In your case you can change from componentDidUpdate to componentDidMount if you only want to do this on the initial render.
I'm struggling with how to do this with functional components. I have this above the return statement:
const scrollbar = React.createRef();
useEffect(() => {
scrollbar.scrollToTop();
});
And in the return:
<Scrollbars
// This will activate auto hide
autoHide
// Hide delay in ms
autoHideTimeout={1000}
// Duration for hide animation in ms.
autoHideDuration={200}
ref={(scrollbar) => {
scrollbar = scrollbar;
}}
>
Error I'm getting is TypeError: scrollbar.scrollToTop is not a function
@dmikester1
I'm no longer using this package so I can't confirm my solution works, but your ref doesn't look like it's correct for React 16.3 and above (see docs). I think you want this:
const scrollbar = React.createRef();
useEffect(() => {
scrollbar.current.scrollToTop();
});
<Scrollbars
autoHide
autoHideTimeout={1000}
autoHideDuration={200}
ref={scrollbar}
>
@knightjdr Thanks! That helped a lot. I had to add a check in the useEffect too.
useEffect(() => {
if (scrollbar.current) {
scrollbar.current.scrollToTop();
}
});