Skip to content

Commit 8b089b6

Browse files
committed
feat: add ScrollToTop
1 parent 178fc0f commit 8b089b6

File tree

2 files changed

+58
-36
lines changed

2 files changed

+58
-36
lines changed

packages/smooth-core/src/client/Routes.js

Lines changed: 39 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,48 +3,51 @@ import { Switch, Route } from 'react-router-dom'
33
import Page, { getPages } from './Page'
44
import HiddenRouter from '../router/HiddenRouter'
55
import { Provider as HiddenHistoryContextProvider } from '../router/HiddenHistoryContext'
6+
import ScrollToTop from '../router/ScrollToTop'
67

78
const pages = getPages()
89

910
export default function Routes() {
1011
return (
1112
<HiddenHistoryContextProvider>
12-
<Route
13-
path="/:lang(.{2})?"
14-
render={({
15-
match: {
16-
url,
17-
params: { lang = null },
18-
},
19-
}) => {
20-
const routes = (
21-
<Switch>
22-
{pages.map((page, index) => (
23-
<Route
24-
key={index}
25-
path={`${url}${page.routePath}`.replace(/^\/\//, '/')}
26-
render={({ history, match, location }) => (
27-
<Page
28-
lang={lang}
29-
indexUrl={`${url}${page.indexPath}`}
30-
page={page}
31-
history={history}
32-
match={match}
33-
location={location}
34-
/>
35-
)}
36-
/>
37-
))}
38-
</Switch>
39-
)
40-
return (
41-
<>
42-
{routes}
43-
<HiddenRouter>{routes}</HiddenRouter>
44-
</>
45-
)
46-
}}
47-
/>
13+
<ScrollToTop>
14+
<Route
15+
path="/:lang(.{2})?"
16+
render={({
17+
match: {
18+
url,
19+
params: { lang = null },
20+
},
21+
}) => {
22+
const routes = (
23+
<Switch>
24+
{pages.map((page, index) => (
25+
<Route
26+
key={index}
27+
path={`${url}${page.routePath}`.replace(/^\/\//, '/')}
28+
render={({ history, match, location }) => (
29+
<Page
30+
lang={lang}
31+
indexUrl={`${url}${page.indexPath}`}
32+
page={page}
33+
history={history}
34+
match={match}
35+
location={location}
36+
/>
37+
)}
38+
/>
39+
))}
40+
</Switch>
41+
)
42+
return (
43+
<>
44+
{routes}
45+
<HiddenRouter>{routes}</HiddenRouter>
46+
</>
47+
)
48+
}}
49+
/>
50+
</ScrollToTop>
4851
</HiddenHistoryContextProvider>
4952
)
5053
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { useEffect, useRef } from 'react'
2+
import { withRouter } from 'react-router-dom'
3+
4+
function ScrollToTop({ children, location }) {
5+
const previousLocation = useRef()
6+
useEffect(() => {
7+
if (
8+
previousLocation.current &&
9+
previousLocation.current.pathname !== location.pathname
10+
) {
11+
// eslint-disable-next-line
12+
window.scrollTo(0, 0)
13+
}
14+
previousLocation.current = location.pathname
15+
}, [location.pathname])
16+
return children
17+
}
18+
19+
export default withRouter(ScrollToTop)

0 commit comments

Comments
 (0)