Skip to content

Commit

Permalink
Merge pull request #27492 from teneeto/chore/16224-migrate-with-viewp…
Browse files Browse the repository at this point in the history
…ort-offset-top-file-to-function-component

chore: migrate withViewportOffsetTop.js class to function component
  • Loading branch information
amyevans authored Oct 12, 2023
2 parents 34c2a27 + d36e26f commit 2c9c303
Showing 1 changed file with 26 additions and 36 deletions.
62 changes: 26 additions & 36 deletions src/components/withViewportOffsetTop.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 (
<WrappedComponent
// eslint-disable-next-line react/jsx-props-no-spreading
{...this.props}
ref={this.props.forwardedRef}
viewportOffsetTop={this.state.viewportOffsetTop}
/>
);
}
return () => {
removeViewportResizeListener();
};
}, []);

return (
<WrappedComponent
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
ref={props.forwardedRef}
viewportOffsetTop={viewportOffsetTop}
/>
);
}

WithViewportOffsetTop.displayName = `WithViewportOffsetTop(${getComponentDisplayName(WrappedComponent)})`;
Expand All @@ -59,7 +49,7 @@ export default function (WrappedComponent) {
WithViewportOffsetTop.defaultProps = {
forwardedRef: undefined,
};
return React.forwardRef((props, ref) => (
return forwardRef((props, ref) => (
<WithViewportOffsetTop
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
Expand Down

0 comments on commit 2c9c303

Please sign in to comment.