Created
August 11, 2019 12:44
-
-
Save Weiyuan-Lane/2db0050d18a0d58c6962fc9df3d81e8e to your computer and use it in GitHub Desktop.
Wrapper for 'next/link' to introduce a base path
This file contains hidden or 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 Link from 'next/link'; | |
import PropTypes from 'prop-types' | |
import getConfig from 'next/config' | |
const { publicRuntimeConfig } = getConfig() | |
const basePath = publicRuntimeConfig.basePath || '' | |
const basePathEndsWithSlash = basePath.endsWith('/') | |
export default function BasePathLink({ href, children, ...props }){ | |
let finalHref | |
if (basePathEndsWithSlash || href.startsWith('/')) { | |
finalHref = `${basePath}${href}` | |
} else { | |
finalHref = `${basePath}/${href}` | |
} | |
return ( | |
<Link | |
href={href} | |
as={finalHref} | |
{...props}> | |
{children} | |
</Link> | |
) | |
} | |
BasePathLink.propTypes = { | |
href: PropTypes.string.isRequired, | |
} | |
Hey dkarski!
I believe that both methodology would read the same, since the conditional check has to be introduced either way.
But I could have removed any trailing /
from basePath and remove any initial /
character from href, and do the following:
finalHref = `${basePath}/${href}`
No conditional checks. What do you think?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Weiyuan Liu, thanks for your article. I came up with a suggestion while reading yours.
In my opinion, concatenate with
/
or without isn't readable. What do you think about setting the initialfinalHref
variable withbasePath
?