The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Scroll to the page top after rendering a React component

posted on 24.4.2023 by Below Surface in "React"

After navigating from one page of my single page application (SPA), the scroll position was not the page top, as expected. The simple working solution i found, is this:

useEffect(() => {
    window.scrollTo(0, 0);
}, []);

The useEffect hook will be needed to imported at the file top like this:

import React, { useEffect } from 'react';

Tags:

React
Next.js
useEffect

Sources:

https://stackoverflow.com/questions/33188994/scroll-to-the-top-of-the-page-after-render-in-react-js

More posts of this category

Conditionally add a HTML attribute in React

How to add a HTML attribute like "selected" to a HTML element

React

How to pass variables down to child components

Work with props in React/Next.js with TypeScript

React

An easy and elegant way to change a boolean useState value

How to toggle a useState boolean value easily

React

How I fixed the auto scroll bug of ReactQuill

Quill is a nice WYSIWYG text editor, but had a weird scroll bug

React