Skip to content

Commit 7d56bc3

Browse files
authored
Support basePath for relative href prop (#248)
* Support basePath for href prop * no basePath for external links * rename external to absolute * match links with no protocol * linting * add changeset
1 parent f00a3fe commit 7d56bc3

File tree

4 files changed

+54
-3
lines changed

4 files changed

+54
-3
lines changed

.changeset/happy-fireants-visit.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-resource-router": patch
3+
---
4+
5+
Support basePath for relative href prop

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/ui/link/index.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,12 @@ const Link = forwardRef<HTMLButtonElement | HTMLAnchorElement, LinkProps>(
7272
)) ||
7373
''
7474
: to;
75+
const IS_ABSOLUTE_LINK_REGEX = /^((?:(http|https):\/\/)|\/\/)/;
7576
const staticBasePath =
76-
href == null && typeof to === 'string' ? routeAttributes.basePath : '';
77+
(href != null && !IS_ABSOLUTE_LINK_REGEX.test(href)) ||
78+
typeof to === 'string'
79+
? routeAttributes.basePath
80+
: '';
7781

7882
const triggerPrefetch = useCallback(() => {
7983
// ignore if async route not ready yet

src/ui/link/test.tsx

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,48 @@ describe('<Link />', () => {
9191
);
9292
});
9393

94+
it('should push history with correct link for relative href when given basePath', () => {
95+
renderInRouter(
96+
'my link',
97+
{
98+
href: '/route/1?foo=bar',
99+
},
100+
'/base'
101+
);
102+
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
103+
'href',
104+
'/base/route/1?foo=bar'
105+
);
106+
});
107+
108+
it('should not add basePath for absolute links', () => {
109+
renderInRouter(
110+
'my link',
111+
{
112+
href: 'https://www.atlassian.com/',
113+
},
114+
'/base'
115+
);
116+
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
117+
'href',
118+
'https://www.atlassian.com/'
119+
);
120+
});
121+
122+
it('should not add basePath for absolute links with no protocol specified', () => {
123+
renderInRouter(
124+
'my link',
125+
{
126+
href: '//www.atlassian.com/',
127+
},
128+
'/base'
129+
);
130+
expect(screen.getByRole('link', { name: 'my link' })).toHaveAttribute(
131+
'href',
132+
'//www.atlassian.com/'
133+
);
134+
});
135+
94136
it('should pass props to the child element', () => {
95137
renderInRouter('my link', {
96138
...defaultProps,

0 commit comments

Comments
 (0)