This is below sample code in which I am facing scroll to top issue whenever user is interacting.
I have added the dummy space with the help of padding on top and bottom, so that whenever user interact, it should always scroll into view. So how can I achieve scroll into view with below code ?
Here content is dynamic, sometime it can be little bit more or less, I am always wanted into view part.
Currently what happening in the application, when we click on next button (assume we have quiz QA) , it automatically scroll to the top and we don’t have such kind of function in application which move toward the top upon navigating question in the quiz. So, I always wanted into the view part.
That’s the reason I added dummy space to replicate the issue which I am facing
return (
<div>
<div style={{padding: 400px, background: #eee}}> Dummy Space
</div>
<div id="show-content">
{/* inside this div I mounting my react app component assume, I have some quiz question along with some button prev and next */}
</div>
<div style={{padding: 400px, background: #eee}}> Dummy Space
</div>
</div>
)
}
You might be saying to remove dummy space related stuff, but there are some other app exist in those area in which I don’t have control over there
2
Answers
Create a
ref
and and use it on the#show-content
div. Scroll to it usingscrollIntoView
.If you navigate from another route, use the following code in the same componenet as the
#show-content
div:If you are on the same route, call
scrollToElement
inonClick
.Use the
ref
object like this:You can use
window.scrollTo(x,y)
if know the height of the component/view. you can use this in built browser function when your component mounts: