Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: migrate withViewportOffsetTop.js class to function component #27492

Merged
merged 4 commits into from
Oct 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading