Going to a section of a page using java script


Going to a section of a page using java script



I have a webpage with several components that looks like:


<div id='someId' ...... />



Manually it is possible to go to those sections using


<a href="#someId" ..... />



How, using es2015 or react or javascript, could be created a function to go to that <div> component ?


<div>




2 Answers
2



You could use the scrollIntoView function.


document.getElementById('someId').scrollIntoView();



React Example (CodeSandbox)


class App extends React.Component {
onClick = () => {
this.ref.scrollIntoView();
};
render() {
return (
<div>
<button onClick={this.onClick}>Scroll down</button>
<div style={{ height: 1000 }}>Hello CodeSandbox</div>
<div style={{ height: 1000 }} ref={ref => (this.ref = ref)}>
Scroll here
</div>
</div>
);
}
}



If you don't mind installing a 3rd party package, I would suggest trying react-scroll-into-view


react-scroll-into-view






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter