forked from icd2k3/react-scroll-into-view-if-needed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (82 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { createElement, createRef, PureComponent } from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line import/no-extraneous-dependencies
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed';
export default class ScrollIntoViewIfNeeded extends PureComponent {
constructor() {
super();
this.node = createRef();
}
componentDidMount() {
const { active } = this.props;
if (active) {
this.handleScrollIntoViewIfNeeded();
}
}
componentDidUpdate({ active }) {
const { active: isNowActive } = this.props;
if (!active && isNowActive) {
this.handleScrollIntoViewIfNeeded();
}
}
handleScrollIntoViewIfNeeded = () => {
const { options } = this.props;
const { current: node } = this.node;
scrollIntoViewIfNeeded(node, options);
};
render() {
const {
active,
elementType,
children,
options,
...wrapperProps
} = this.props;
return createElement(elementType, { ref: this.node, ...wrapperProps }, children);
}
}
ScrollIntoViewIfNeeded.propTypes = {
active: PropTypes.bool,
children: PropTypes.node.isRequired,
elementType: PropTypes.string,
// this shape should mirror the scroll-into-view-if-needed options
options: PropTypes.shape({
behavior: PropTypes.oneOfType([
PropTypes.oneOf([
'auto',
'smooth',
'instant',
]),
PropTypes.func,
]),
block: PropTypes.oneOf([
'center',
'end',
'nearest',
'start',
]),
inline: PropTypes.oneOf([
'center',
'end',
'nearest',
'start',
]),
scrollMode: PropTypes.oneOf([
'always',
'if-needed',
]),
boundary: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func,
]),
skipOverflowHiddenElements: PropTypes.bool,
}),
};
ScrollIntoViewIfNeeded.defaultProps = {
active: true,
elementType: 'div',
options: {
behavior: 'smooth',
scrollMode: 'if-needed',
},
};