HOC and hook implemented for location hash

This commit is contained in:
NikolaBorislavovHristov 2019-04-22 16:57:04 +03:00
parent 718660d117
commit 7d5f7537f7
3 changed files with 35 additions and 1 deletions

View file

@ -6,6 +6,8 @@ const NavBar = require('./NavBar');
const Popup = require('./Popup');
const ShareModal = require('./ShareModal');
const Slider = require('./Slider');
const useLocationHash = require('./useLocationHash');
const withLocationHash = require('./withLocationHash');
module.exports = {
Checkbox,
@ -15,5 +17,7 @@ module.exports = {
NavBar,
Popup,
ShareModal,
Slider
Slider,
useLocationHash,
withLocationHash
};

View file

@ -0,0 +1,17 @@
const React = require('react');
const useLocationHash = () => {
const [locationHash, setLocationHash] = React.useState(window.location.hash);
const onLocationHashChanged = React.useCallback(() => {
setLocationHash(window.location.hash);
}, []);
useEffect(() => {
window.addEventListener('hashchange', onLocationHashChanged);
return () => {
window.removeEventListener('hashchange', onLocationHashChanged);
};
}, []);
return locationHash;
};
module.exports = useLocationHash;

View file

@ -0,0 +1,13 @@
const React = require('react');
const useLocationHash = require('./useLocationHash');
const withLocationHash = (Component) => {
return (props) => {
const locationHash = useLocationHash();
return (
<Component {...props} locationHash={locationHash} />
);
};
};
module.exports = withLocationHash;