Skip to content

Commit 723d5f5

Browse files
committed
feat: move scroll to top from link to middleware
1 parent 32802c9 commit 723d5f5

File tree

3 files changed

+14
-14
lines changed

3 files changed

+14
-14
lines changed

src/actions/changePageTo.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { CHANGE_PAGE_TO } from '../constants';
22

3-
const changePageTo = ( to, { shouldAddToHistory = true } = {}) => ({
4-
options: { shouldAddToHistory },
3+
const changePageTo = ( to, { shouldAddToHistory = true, shouldScrollToTop = true } = {}) => ({
4+
options: { shouldAddToHistory, shouldScrollToTop },
55
type: CHANGE_PAGE_TO,
66
to,
77
});

src/components/Link.js

+3-11
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,14 @@ import changePageTo from '../actions/changePageTo';
55
import getLocation from '../helpers/getLocation';
66

77
const defaultProps = {
8+
shouldAddToHistory: true,
89
shouldScrollToTop: true,
910
};
1011

11-
const scrollToTop = () => {
12-
document.documentElement.scrollTop = document.body.scrollTop = 0;
13-
};
14-
15-
const Link = ({ children, dispatch, shouldScrollToTop, to, ...props }) => {
12+
const Link = ({ children, dispatch, shouldAddToHistory, shouldScrollToTop, to, ...props }) => {
1613
const onClick = e => {
1714
e.preventDefault();
18-
19-
dispatch( changePageTo( to ));
20-
21-
if ( shouldScrollToTop ) {
22-
scrollToTop();
23-
}
15+
dispatch( changePageTo( to, { shouldAddToHistory, shouldScrollToTop }));
2416
};
2517

2618
return (

src/middleware/router.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import getAction from '../helpers/getAction';
22
import popStateListener from '../helpers/popStateListener';
33
import { CHANGE_PAGE_TO } from '../constants';
44

5+
const scrollToTop = () => {
6+
document.documentElement.scrollTop = document.body.scrollTop = 0;
7+
};
8+
59
const router = ( routes, { isServer = false } = {}) => ({ dispatch }) => {
610
if ( !isServer ) {
711
popStateListener( dispatch );
@@ -11,14 +15,18 @@ const router = ( routes, { isServer = false } = {}) => ({ dispatch }) => {
1115
const { type } = initialAction;
1216

1317
if ( type === CHANGE_PAGE_TO ) {
14-
const { options: { shouldAddToHistory }, to } = initialAction;
18+
const { options: { shouldAddToHistory, shouldScrollToTop }, to } = initialAction;
1519

1620
const action = getAction( to, routes );
1721

1822
if ( !isServer && shouldAddToHistory ) {
1923
window.history.pushState({}, '', action.url );
2024
}
2125

26+
if ( shouldScrollToTop ) {
27+
scrollToTop();
28+
}
29+
2230
return next( action );
2331
}
2432

0 commit comments

Comments
 (0)