react-custom-scrollbars icon indicating copy to clipboard operation
react-custom-scrollbars copied to clipboard

Manual scroll top reset is not working

Open BlackBeast opened this issue 7 years ago • 6 comments

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.

BlackBeast avatar Jan 18 '18 10:01 BlackBeast

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 avatar Feb 20 '18 16:02 knightjdr

@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 avatar Jun 21 '18 10:06 sridhar37

@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.

knightjdr avatar Jul 20 '18 15:07 knightjdr

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 avatar Feb 12 '20 13:02 dmikester1

@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 avatar Feb 12 '20 15:02 knightjdr

@knightjdr Thanks! That helped a lot. I had to add a check in the useEffect too.

useEffect(() => {
	if (scrollbar.current) {
		scrollbar.current.scrollToTop();
	}
});

dmikester1 avatar Feb 12 '20 16:02 dmikester1