Keep scroll postion ReactJS

Tram Ho

Hello everyone, it’s me again. Today I would like to share with you a feature that when going to work will be able to meet, this feature I have just discovered, on google there are quite a lot of articles about it, but for these few posts I will myself code and hope to help you.

Did you notice when shoppe looking for a certain product it will have a long list of many sp, when you scroll down and click on any sp, then back it up, it still remains at the position that I scrolled before that? Here I will proceed to make an example so that you can imagine it more easily, please follow me:

1. Create a project:

First, run this command to initialize a project using create-react-app :

Once created, run it with the command below to check if your project has run yet:

2. Install React router:

To use React router, you need to install react-router-dom package for yourself:

3. Create files:

After the installation is complete you proceed to create two more pages for yourself in Home.js and Product.js in ./src In the Home.js and Product.js files, I will give the same difference only in the component name:

Let me explain a little more about the above code, you can see that I am importing useKeepPositionScroll (I will explain about this guy). Here I want to create a list with 20 items so I created with Array.from(new Array(20), (_, i) => i); Then use map to show it.

Next, I will proceed to create a menu to click to switch pages. First create components / Navbar / index.js with the following code:

The above code is also simple so I do not explain more.

Then go to the App.js file to let me configure the router.

If you are not familiar with React router, you can read more here , easy to understand

Then run it to see if it is ok!

Then finally is the custom hook useKeepPositionScroll.js , you create yourself /hooks/index.js with the code:

Then create /hooks/useKeepPositionScroll.js :

The above code is that I am creating a custom hook, this file has the function of checking if the pathname of this page already exists in sessionStorage, if not, add it, but then it will be replaced with another value. Its structure means like this:

In the above code, I have noted cmt so the readers will understand.

4. Conclusion:

It’s all over, hope it will be helpful for you guys, have a nice weekend, thanks all

Share the news now

Source : Viblo