Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1224 | useSref | updated onClick to check target from currentProperty to let browser handle clicks #1226

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/hooks/__tests__/useSref.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<a data-testid="anchor" {...sref} target={target}>
<div data-testid="inner-child">{children}</div>
</a>
);
};

describe('useSref', () => {
let { router, routerGo, mountInRouter } = makeTestRouter([]);
beforeEach(() => ({ router, routerGo, mountInRouter } = makeTestRouter([state, state2, state3])));
Expand Down Expand Up @@ -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(<LinkWithChildElement to="state" target="_blank" />);

// 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', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/hooks/useSref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down