Skip to content

Instantly share code, notes, and snippets.

@jamesblashill
Created October 3, 2019 20:42
Show Gist options
  • Save jamesblashill/16e086ea267340ac46d5f6d26344a7b8 to your computer and use it in GitHub Desktop.
Save jamesblashill/16e086ea267340ac46d5f6d26344a7b8 to your computer and use it in GitHub Desktop.
Hooks vs class component
export const ScrollIntoView: React.FC<IProps> = memo(
withRouter<IWithRouterProps, React.FC<IWithRouterProps>>(
({ id, className, children, top, location }) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (location.hash === `#${id}` && ref.current) {
ref.current.scrollIntoView();
}
}, [location]);
return (
<Container id={id} className={className} top={top} ref={ref}>
{children}
</Container>
);
}
)
);
class ScrollIntoViewClass extends React.Component<IWithRouterProps> {
private ref = React.createRef<HTMLDivElement>();
scrollIntoViewIfRequested = () => {
const { id, location } = this.props;
if (location.hash === `#${id}` && this.ref.current) {
this.ref.current.scrollIntoView();
}
};
componentDidMount() {
this.scrollIntoViewIfRequested();
}
componentDidUpdate(prevProps: IWithRouterProps) {
if (prevProps.location.hash !== this.props.location.hash) {
this.scrollIntoViewIfRequested();
}
}
render() {
const { id, className, children, top } = this.props;
return (
<Container id={id} className={className} top={top} ref={this.ref}>
{children}
</Container>
);
}
}
export const ScrollIntoView: React.ComponentClass<IProps> = withRouter(
ScrollIntoViewClass
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment