Last active
January 12, 2023 17:42
-
-
Save laurenzcodes/5c0280b834cc0dba1451cdbbde29f6e3 to your computer and use it in GitHub Desktop.
Gatsby Link Component that preserves url parameters after route change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
import { Link as GatsbyLink, GatsbyLinkProps } from 'gatsby' | |
interface Props extends GatsbyLinkProps<HTMLAnchorElement> { | |
to: string | |
className?: string | |
target?: string | |
} | |
const checkLinkType = (to: Props['to']) => { | |
return /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g.test( | |
to | |
) | |
} | |
// Remove duplicate URL Params | |
const removeDuplicate = (url) => { | |
url = decodeURIComponent(url) | |
const query = url.split('?')[1] | |
const parts = query.split('&') | |
const params = {} | |
// eslint-disable-next-line @typescript-eslint/prefer-for-of | |
for (let i = 0; i < parts.length; i++) { | |
const nv = parts[i].split('=') | |
if (!nv[0]) { | |
continue | |
} | |
const value = nv[1] || true | |
if (params[nv[0]] && params[nv[0]].indexOf(value)) { | |
params[nv[0]].push(value) | |
} else { | |
params[nv[0]] = [value] | |
} | |
} | |
url = url.split('?')[0] + '?' | |
const keys = Object.keys(params) | |
for (let i = 0; i < keys.length; i++) { | |
url += keys[i] + '=' + params[keys[i]][0] | |
if (i !== keys.length - 1) { | |
url += '&' | |
} | |
} | |
return url | |
} | |
const Link: React.FunctionComponent<Props> = ({ | |
to, | |
className, | |
target, | |
...props | |
}) => { | |
if (typeof window !== 'undefined') { | |
const link = to.includes('?') | |
? removeDuplicate(to + location.search.replace('?', '&')) | |
: to + location.search | |
if (checkLinkType(to)) { | |
return ( | |
<a | |
className={className} | |
href={link} | |
target={target ? target : '_blank'} | |
rel="noopener noreferrer" | |
onClick={props.onClick} | |
> | |
{props.children} | |
</a> | |
) | |
} | |
return ( | |
<GatsbyLink className={className} to={link} onClick={props.onClick}> | |
{props.children} | |
</GatsbyLink> | |
) | |
} | |
return null | |
} | |
export default Link |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this component retain the activeStyle class?
I have noticed that the activeStyle class doesn't apply when you add query-string to the URl.