forked from trevorr/react-scroll-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElementScroller.js
52 lines (43 loc) · 1.29 KB
/
ElementScroller.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
import React from 'react';
import PropTypes from 'prop-types';
import { ScrollManager, withManager } from './ScrollManager';
class ManagedElementScroller extends React.Component {
constructor(props) {
super(props);
this._ref = React.createRef();
}
componentDidMount() {
this._register();
}
componentWillUnmount() {
this._unregister(this.props);
}
componentDidUpdate(prevProps) {
this._unregister(prevProps);
this._register();
}
_register() {
const { manager, scrollKey } = this.props;
const node = this._ref.current;
if (!manager) {
console.warn('ElementScroller only works when nested within a ScrollManager'); // eslint-disable-line no-console
} else if (scrollKey && node) {
manager._registerElement(scrollKey, node);
}
}
_unregister(props) {
const { manager, scrollKey } = props;
if (manager && scrollKey) {
manager._unregisterElement(scrollKey);
}
}
render() {
return React.cloneElement(React.Children.only(this.props.children), { ref: this._ref });
}
}
ManagedElementScroller.propTypes = {
manager: PropTypes.instanceOf(ScrollManager).isRequired,
scrollKey: PropTypes.string.isRequired,
children: PropTypes.element.isRequired
};
export const ElementScroller = withManager(ManagedElementScroller);