Skip to content

Commit

Permalink
Support basePath for relative href prop (#248)
Browse files Browse the repository at this point in the history
* Support basePath for href prop

* no basePath for external links

* rename external to absolute

* match links with no protocol

* linting

* add changeset
  • Loading branch information
upreeti authored Feb 3, 2025
1 parent f00a3fe commit 7d56bc3
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/happy-fireants-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-resource-router": patch
---

Support basePath for relative href prop
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion src/ui/link/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,12 @@ const Link = forwardRef<HTMLButtonElement | HTMLAnchorElement, LinkProps>(
)) ||
''
: to;
const IS_ABSOLUTE_LINK_REGEX = /^((?:(http|https):\/\/)|\/\/)/;
const staticBasePath =
href == null && typeof to === 'string' ? routeAttributes.basePath : '';
(href != null && !IS_ABSOLUTE_LINK_REGEX.test(href)) ||
typeof to === 'string'
? routeAttributes.basePath
: '';

const triggerPrefetch = useCallback(() => {
// ignore if async route not ready yet
Expand Down
42 changes: 42 additions & 0 deletions src/ui/link/test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,48 @@ describe('<Link />', () => {
);
});

it('should push history with correct link for relative href when given basePath', () => {
renderInRouter(
'my link',
{
href: '/route/1?foo=bar',
},
'/base'
);
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
'href',
'/base/route/1?foo=bar'
);
});

it('should not add basePath for absolute links', () => {
renderInRouter(
'my link',
{
href: 'https://www.atlassian.com/',
},
'/base'
);
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
'href',
'https://www.atlassian.com/'
);
});

it('should not add basePath for absolute links with no protocol specified', () => {
renderInRouter(
'my link',
{
href: '//www.atlassian.com/',
},
'/base'
);
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
'href',
'//www.atlassian.com/'
);
});

it('should pass props to the child element', () => {
renderInRouter('my link', {
...defaultProps,
Expand Down

0 comments on commit 7d56bc3

Please sign in to comment.