Sauvegarde de la position de scroll page suivante/précédente (#2273)
* feat: add useSaveScrollPosition hook + CustomRouter * fix: Remplace useLayoutEffect par useEffect * feat: remplace l'usage d'history par un event listener * chore: Renommage du hookpull/2277/head
parent
3b57fc87de
commit
d922734f93
|
@ -23,6 +23,7 @@ import { useTranslation } from 'react-i18next'
|
|||
import { useSelector } from 'react-redux'
|
||||
import { Route, Routes } from 'react-router-dom'
|
||||
import styled, { css } from 'styled-components'
|
||||
import { useSaveAndRestoreScrollPosition } from './hooks/useSaveAndRestoreScrollPosition'
|
||||
import Accessibilité from './pages/Accessibilité'
|
||||
import Budget from './pages/Budget/Budget'
|
||||
import Créer from './pages/Creer'
|
||||
|
@ -109,6 +110,8 @@ const App = () => {
|
|||
const { relativeSitePaths } = useSitePaths()
|
||||
const isEmbedded = useIsEmbedded()
|
||||
|
||||
useSaveAndRestoreScrollPosition()
|
||||
|
||||
return (
|
||||
<StyledLayout isEmbeded={isEmbedded}>
|
||||
{!isEmbedded && <Header />}
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
import { debounce } from '@/utils'
|
||||
import { useEffect } from 'react'
|
||||
import { useLocation, useNavigationType } from 'react-router-dom'
|
||||
|
||||
const POP_ACTION_LABEL = 'POP'
|
||||
|
||||
export const useSaveAndRestoreScrollPosition = () => {
|
||||
const location = useLocation()
|
||||
const navigationType = useNavigationType()
|
||||
|
||||
useEffect(() => {
|
||||
const scrollPosition = sessionStorage.getItem(location.pathname)
|
||||
|
||||
if (scrollPosition && navigationType === POP_ACTION_LABEL) {
|
||||
window.scrollTo(0, parseInt(scrollPosition))
|
||||
}
|
||||
}, [location, navigationType])
|
||||
|
||||
useEffect(() => {
|
||||
const saveScrollYPosition = debounce(100, () => {
|
||||
sessionStorage.setItem(location.pathname, String(window.scrollY))
|
||||
}) as (this: Window, ev: Event) => any
|
||||
|
||||
window.addEventListener('scroll', saveScrollYPosition)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', saveScrollYPosition)
|
||||
}
|
||||
}, [location.pathname])
|
||||
}
|
Loading…
Reference in New Issue