From 7d5f7537f761497aa75aae85923f85e8a0465b83 Mon Sep 17 00:00:00 2001 From: NikolaBorislavovHristov Date: Mon, 22 Apr 2019 16:57:04 +0300 Subject: [PATCH] HOC and hook implemented for location hash --- src/common/index.js | 6 +++++- src/common/useLocationHash.js | 17 +++++++++++++++++ src/common/withLocationHash.js | 13 +++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/common/useLocationHash.js create mode 100644 src/common/withLocationHash.js diff --git a/src/common/index.js b/src/common/index.js index 38b2223bd..903935f11 100644 --- a/src/common/index.js +++ b/src/common/index.js @@ -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 }; diff --git a/src/common/useLocationHash.js b/src/common/useLocationHash.js new file mode 100644 index 000000000..c75b3f66b --- /dev/null +++ b/src/common/useLocationHash.js @@ -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; diff --git a/src/common/withLocationHash.js b/src/common/withLocationHash.js new file mode 100644 index 000000000..b5e6777b8 --- /dev/null +++ b/src/common/withLocationHash.js @@ -0,0 +1,13 @@ +const React = require('react'); +const useLocationHash = require('./useLocationHash'); + +const withLocationHash = (Component) => { + return (props) => { + const locationHash = useLocationHash(); + return ( + + ); + }; +}; + +module.exports = withLocationHash;