Skip to content

Commit e690193

Browse files
authored
Merge pull request #2318 from dxc-technology/PelayoFelgueroso/quickNav-routing
Fix Quick Nav bug with HashRouter
2 parents 10cdc6e + d135b68 commit e690193

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

apps/website/screens/components/quick-nav/code/QuickNavCodePage.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ const sections = [
3333
</td>
3434
<td>
3535
Links of the quick nav component. Only first and second level links will be shown in the quick nav, due to
36-
design restrictions. Each link has the following properties:
36+
design restrictions. The component automatically detects HashRouter usage and enables smooth scrolling
37+
navigation when appropriate. Each link has the following properties:
3738
<ul>
3839
<li>
3940
<b>label</b>: Text to be shown in the link. The content must be wrapped with an id equal to the

packages/lib/src/quick-nav/QuickNav.tsx

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,29 @@ const Link = styled.a`
6161

6262
export default function DxcQuickNav({ links, title }: QuickNavTypes) {
6363
const translatedLabels = useContext(HalstackLanguageContext);
64+
const isHashRouter = (): boolean => {
65+
if (typeof window === "undefined") return false;
66+
return window.location.href.includes("/#/");
67+
};
6468

6569
return (
6670
<QuickNavContainer>
6771
<DxcHeading level={5} text={title ?? translatedLabels.quickNav.contentTitle} />
6872
<ListColumn>
6973
{links.map((link) => (
7074
<li key={link.label}>
71-
<Link href={`#${slugify(link.label, { lower: true })}`}>
75+
<Link
76+
href={`#${slugify(link.label, { lower: true })}`}
77+
onClick={
78+
isHashRouter()
79+
? (e) => {
80+
e.preventDefault();
81+
const id = slugify(link.label, { lower: true });
82+
document.getElementById(id)?.scrollIntoView();
83+
}
84+
: undefined
85+
}
86+
>
7287
<span>{link.label}</span>
7388
</Link>
7489
{link.links?.length && (
@@ -79,6 +94,15 @@ export default function DxcQuickNav({ links, title }: QuickNavTypes) {
7994
href={`#${slugify(link?.label, { lower: true })}-${slugify(sublink?.label, {
8095
lower: true,
8196
})}`}
97+
onClick={
98+
isHashRouter()
99+
? (e) => {
100+
e.preventDefault();
101+
const id = `${slugify(link.label, { lower: true })}-${slugify(sublink.label, { lower: true })}`;
102+
document.getElementById(id)?.scrollIntoView();
103+
}
104+
: undefined
105+
}
82106
>
83107
<span>{sublink.label}</span>
84108
</Link>

0 commit comments

Comments
 (0)