Skip to content

Commit 2b80ed8

Browse files
MichaelDeBoeySaraVieira
authored andcommitted
Refactor LoadInView to functional component with hooks (codesandbox#1942)
1 parent 4a2cebb commit 2b80ed8

File tree

1 file changed

+33
-39
lines changed

1 file changed

+33
-39
lines changed
Lines changed: 33 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,42 @@
1-
import React from 'react';
21
import { debounce } from 'lodash-es';
2+
import React, { useCallback, useEffect, useRef, useState } from 'react';
33

44
import getScrollPos from '../utils/scroll';
55

6-
export default class LoadInView extends React.PureComponent {
7-
state = {
8-
show: false,
9-
};
6+
const LoadInView = ({ children, style, ...props }) => {
7+
const [show, setShow] = useState(false);
8+
const el = useRef(null);
9+
const elPos = useRef(null);
1010

11-
constructor(props) {
12-
super(props);
13-
this.listen = debounce(this.listen, 50);
14-
}
11+
useEffect(() => {
12+
elPos.current = el.current.getBoundingClientRect().top;
13+
}, []);
1514

16-
listen = () => {
17-
if (!this.state.show && this.elPos && getScrollPos().y + 600 > this.elPos) {
15+
const listenFn = useCallback(() => {
16+
if (!show && elPos.current && getScrollPos().y + 600 > elPos.current) {
1817
requestAnimationFrame(() => {
19-
this.setState({ show: true });
18+
setShow(true);
2019
});
2120
}
22-
};
23-
24-
componentDidMount() {
25-
this.elPos = this.el.getBoundingClientRect().top;
26-
27-
window.addEventListener('scroll', this.listen);
28-
}
29-
30-
componentWillUnmount() {
31-
window.removeEventListener('scroll', this.listen);
32-
}
33-
34-
render() {
35-
const { children, style, ...props } = this.props;
36-
return (
37-
<div
38-
style={{ display: 'inline-block', width: '100%', ...style }}
39-
ref={el => {
40-
this.el = el;
41-
}}
42-
{...props}
43-
>
44-
{this.state.show && children}
45-
</div>
46-
);
47-
}
48-
}
21+
}, [show]);
22+
23+
useEffect(() => {
24+
const listen = debounce(listenFn, 50);
25+
26+
window.addEventListener('scroll', listen);
27+
28+
return () => window.removeEventListener('scroll', listen);
29+
}, [listenFn]);
30+
31+
return (
32+
<div
33+
ref={el}
34+
style={{ display: 'inline-block', width: '100%', ...style }}
35+
{...props}
36+
>
37+
{show && children}
38+
</div>
39+
);
40+
};
41+
42+
export default LoadInView;

0 commit comments

Comments
 (0)