ReactJs Scroll To Top


We can use navigator location property to scroll to top of the page. Here in this tutorial, we are going to explain how you can use the navigator location property in ReactJs. You can also use our online editor to edit and run the code online.


ReactJs Scroll To Top Method Example

You can create button to “Go to top” simply as below-

Example:

<script>
function MyFunction() {
  const currUrl = "Current Url = "+window.location.href;  
  return (
    <div style={{height:'800px', background:"yellow", padding: "50px"}}>
	<div style={{height:'700px'}}>
	<p>Click the Below Button to scroll top.</p>
	</div>
    <button onClick={TestFunction} style={{background:"skyblue", padding:"10px", margin:"0 auto"}}>
        Click Me
     </button>
	
	</div>
  );
}
function TestFunction() {
  location.href = "#top";
}

const myData = '';
ReactDOM.render(
  <MyFunction />,
  document.getElementById('root')
);


</script>

Try it »


Advertisements

Add Comment

📖 Read More