Updated ScrollToTop to be a functional component

This commit is contained in:
Alejandro Celaya 2020-05-31 09:50:00 +02:00
parent b7fd2308ad
commit 4bd83eecfb
3 changed files with 17 additions and 21 deletions

View file

@ -18,7 +18,8 @@
"test:ci": "npm run test -- --coverage --coverageReporters=text --coverageReporters=text-summary --coverageReporters=clover", "test:ci": "npm run test -- --coverage --coverageReporters=text --coverageReporters=text-summary --coverageReporters=clover",
"test:pretty": "npm run test -- --coverage --coverageReporters=text --coverageReporters=text-summary --coverageReporters=html", "test:pretty": "npm run test -- --coverage --coverageReporters=text --coverageReporters=text-summary --coverageReporters=html",
"mutate": "./node_modules/.bin/stryker run", "mutate": "./node_modules/.bin/stryker run",
"mutate:ci": "npm run mutate -- --mutate=$MUTATION_FILES" "mutate:ci": "npm run mutate -- --mutate=$MUTATION_FILES",
"check": "npm run test & npm run lint & wait"
}, },
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-free": "^5.11.2", "@fortawesome/fontawesome-free": "^5.11.2",

View file

@ -1,23 +1,23 @@
import React from 'react'; import { useEffect } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
const ScrollToTop = ({ scrollTo }) => class ScrollToTop extends React.Component { const propTypes = {
static propTypes = { location: PropTypes.object,
location: PropTypes.object, children: PropTypes.node,
children: PropTypes.node, };
const ScrollToTop = () => {
const ScrollToTopComp = ({ location, children }) => {
useEffect(() => {
scrollTo(0, 0);
}, [ location ]);
return children;
}; };
componentDidUpdate({ location: prevLocation }) { ScrollToTopComp.propTypes = propTypes;
const { location } = this.props;
if (location !== prevLocation) { return ScrollToTopComp;
scrollTo(0, 0);
}
}
render() {
return this.props.children;
}
}; };
export default ScrollToTop; export default ScrollToTop;

View file

@ -20,9 +20,4 @@ describe('<ScrollToTop />', () => {
}); });
it('just renders children', () => expect(wrapper.text()).toEqual('Foobar')); it('just renders children', () => expect(wrapper.text()).toEqual('Foobar'));
it('scrolls to top when location changes', () => {
wrapper.instance().componentDidUpdate({ location: { href: 'bar' } });
expect(window.scrollTo).toHaveBeenCalledTimes(1);
});
}); });