diff --git a/src/components/withViewportOffsetTop.js b/src/components/withViewportOffsetTop.js index 113c72ed1e1a..ccf928b3bd13 100644 --- a/src/components/withViewportOffsetTop.js +++ b/src/components/withViewportOffsetTop.js @@ -1,4 +1,4 @@ -import React, {Component} from 'react'; +import React, {useEffect, forwardRef, useState} from 'react'; import PropTypes from 'prop-types'; import lodashGet from 'lodash/get'; import getComponentDisplayName from '../libs/getComponentDisplayName'; @@ -13,43 +13,33 @@ const viewportOffsetTopPropTypes = { }; export default function (WrappedComponent) { - class WithViewportOffsetTop extends Component { - constructor(props) { - super(props); - - this.updateDimensions = this.updateDimensions.bind(this); - - this.state = { - viewportOffsetTop: 0, + function WithViewportOffsetTop(props) { + const [viewportOffsetTop, setViewportOffsetTop] = useState(0); + + useEffect(() => { + /** + * @param {SyntheticEvent} e + */ + const updateDimensions = (e) => { + const targetOffsetTop = lodashGet(e, 'target.offsetTop', 0); + setViewportOffsetTop(targetOffsetTop); }; - } - - componentDidMount() { - this.removeViewportResizeListener = addViewportResizeListener(this.updateDimensions); - } - componentWillUnmount() { - this.removeViewportResizeListener(); - } + const removeViewportResizeListener = addViewportResizeListener(updateDimensions); - /** - * @param {SyntheticEvent} e - */ - updateDimensions(e) { - const viewportOffsetTop = lodashGet(e, 'target.offsetTop', 0); - this.setState({viewportOffsetTop}); - } - - render() { - return ( - - ); - } + return () => { + removeViewportResizeListener(); + }; + }, []); + + return ( + + ); } WithViewportOffsetTop.displayName = `WithViewportOffsetTop(${getComponentDisplayName(WrappedComponent)})`; @@ -59,7 +49,7 @@ export default function (WrappedComponent) { WithViewportOffsetTop.defaultProps = { forwardedRef: undefined, }; - return React.forwardRef((props, ref) => ( + return forwardRef((props, ref) => (