diff --git a/packages/webiny-react-router/src/Router.cmp.js b/packages/webiny-react-router/src/Router.cmp.js index 02ba2734844..67b008f103c 100644 --- a/packages/webiny-react-router/src/Router.cmp.js +++ b/packages/webiny-react-router/src/Router.cmp.js @@ -9,6 +9,31 @@ class Router extends React.Component<*, *> { unlisten = null; + clickHandler = (event: Event) => { + // $FlowFixMe + const a = event.path.find(el => el.tagName === "A"); + if (!a) { + return; + } + + if (a.href.endsWith("#") || a.target === "_blank") { + return; + } + + // Check if it's an anchor link + if (a.href.indexOf("#") > -1) { + return; + } + + if (a.href.startsWith(window.location.origin)) { + event.preventDefault(); + const { router } = this.props; + const { history } = router; + let url = parse(a.href, true); + history.push(url.pathname, router.config.basename); + } + }; + componentDidMount() { const { router } = this.props; const { history } = router; @@ -19,29 +44,7 @@ class Router extends React.Component<*, *> { }); }); - document.addEventListener("click", function(event: Event) { - // $FlowFixMe - const a = event.path.find(el => el.tagName === "A"); - if (!a) { - return; - } - - if (a.href.endsWith("#") || a.target === "_blank") { - return; - } - - // Check if it's an anchor link - if (a.href.indexOf("#") > -1) { - return; - } - - if (a.href.startsWith(window.location.origin)) { - event.preventDefault(); - - let url = parse(a.href, true); - history.push(url.pathname, router.config.basename); - } - }); + document.addEventListener("click", this.clickHandler); router.matchRoute(history.location.pathname).then(route => { this.setState({ route }); @@ -59,6 +62,8 @@ class Router extends React.Component<*, *> { componentWillUnmount() { this.unlisten && this.unlisten(); this.unlisten = null; + + document.removeEventListener("click", this.clickHandler); } render() {