How to implement scroll restoration for React Router SPA

前端 未结 1 845
既然无缘
既然无缘 2021-02-20 09:25

I\'m building a React single-page application, and I\'ve noticed the scroll restoration does not appear to work as expected in Chrome (and maybe other browsers.)

On the

相关标签:
1条回答
  • 2021-02-20 10:00

    One way to do this is with oaf-react-router. Use the shouldHandleAction options in the settings. The function gets passed previousLocation and nextLocation which you can use to determine if scroll should be reset/restored, and return false if not.

    const history = createBrowserHistory();
    
    const settings = {
       shouldHandleAction: (previousLocation, nextLocation) => {
           // Inspect/compare nextLocation and/or previousLocation.
           return false // false if you don't want scroll restoration.
       }
    };
    
    wrapHistory(history, settings);
    

    oaf-react-router works with React Router v4 and v5, and handles accessibility, where many SPA routers do not, so it may be the most complete solution at this time.

    Curiously, the documentation does not elaborate on this feature.

    If anyone else has a solution that works and would be considered more of a standard, please provide an answer with it here, and I'll consider changing the selected answer.

    0 讨论(0)
提交回复
热议问题