Skip to content

Commit

Permalink
Fix onRouted not called after click handler
Browse files Browse the repository at this point in the history
  • Loading branch information
maxmilton committed Nov 18, 2021
1 parent 250af7d commit 6b4d907
Showing 1 changed file with 28 additions and 23 deletions.
51 changes: 28 additions & 23 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,6 @@ export function routeTo(
startTransition(() => setUrlPath(/[^#?]*/.exec(url)![0]), callback);
}

function handleClick(event: MouseEvent): void {
if (
event.ctrlKey
|| event.metaKey
|| event.altKey
|| event.shiftKey
|| event.button
|| event.defaultPrevented
) {
return;
}

const link = (event.target as Element).closest('a');
const href = link && link.getAttribute('href');

if (!href || link.target || link.host !== location.host || href[0] === '#') {
return;
}

event.preventDefault();
routeTo(href);
}

export type RouteComponent<P = Record<string, any>> = (
props: P & {
children?: JSX.Element;
Expand All @@ -69,6 +46,34 @@ export const Router: Component<RouterProps> = (props) => {
startTransition(() => setUrlPath(location.pathname), props.onRouted);
};

const handleClick = (event: MouseEvent): void => {
if (
event.ctrlKey
|| event.metaKey
|| event.altKey
|| event.shiftKey
|| event.button
|| event.defaultPrevented
) {
return;
}

const link = (event.target as Element).closest('a');
const href = link && link.getAttribute('href');

if (
!href
|| link.target
|| link.host !== location.host
|| href[0] === '#'
) {
return;
}

event.preventDefault();
routeTo(href, false, props.onRouted);
};

addEventListener('popstate', handleHistoryState);
addEventListener('click', handleClick);

Expand Down

0 comments on commit 6b4d907

Please sign in to comment.