diff --git a/src/hooks/__tests__/useSref.test.tsx b/src/hooks/__tests__/useSref.test.tsx
index 8d8f490e..4f904714 100644
--- a/src/hooks/__tests__/useSref.test.tsx
+++ b/src/hooks/__tests__/useSref.test.tsx
@@ -20,6 +20,15 @@ const Link = ({ to, params = undefined, children = undefined, target = undefined
);
};
+const LinkWithChildElement = ({ to, params = undefined, children = undefined, target = undefined }) => {
+ const sref = useSref(to, params);
+ return (
+
+ {children}
+
+ );
+};
+
describe('useSref', () => {
let { router, routerGo, mountInRouter } = makeTestRouter([]);
beforeEach(() => ({ router, routerGo, mountInRouter } = makeTestRouter([state, state2, state3])));
@@ -83,6 +92,16 @@ describe('useSref', () => {
rendered.getByTestId('anchor').click();
expect(spy).not.toHaveBeenCalled();
});
+
+ it('does not get called if the underlying DOM element that has a child has a "target" attribute', () => {
+ const spy = jest.spyOn(router.stateService, 'go');
+ const rendered = mountInRouter();
+
+ // clicking on the div to mimick the actual behaviour
+ // behaviour: when anchor has a child element and user clicks on anchor, the event is fired on child element rather than on anchor
+ rendered.getByTestId('inner-child').click();
+ expect(spy).not.toHaveBeenCalled();
+ });
});
it('updates the href when the stateName changes', () => {
diff --git a/src/hooks/useSref.ts b/src/hooks/useSref.ts
index 96fcd04e..038808bb 100644
--- a/src/hooks/useSref.ts
+++ b/src/hooks/useSref.ts
@@ -90,7 +90,9 @@ export function useSref(stateName: string, params: object = {}, options: Transit
const onClick = useCallback(
(e: React.MouseEvent) => {
- const targetAttr = (e.target as any)?.attributes?.target;
+ /* We want to check attributes on the element that the click handler is on and not on whichever other element was clicked*/
+
+ const targetAttr = (e.currentTarget as any)?.attributes?.target;
const modifierKey = e.button >= 1 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey;
if (!e.defaultPrevented && targetAttr == null && !modifierKey) {
e.preventDefault();