Last active
August 27, 2022 15:43
-
-
Save zackdotcomputer/d7af9901e7db87364aad7fbfadb5c99b to your computer and use it in GitHub Desktop.
Workaround for next/link vs <a> href accessibility lint issue
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
// Created by Zack Sheppard (@zackdotcomputer) on 1/19/2021 | |
// Freely available under MIT License | |
// Workaround for https://github.com/vercel/next.js/issues/5533 | |
import Link, { LinkProps } from "next/link"; | |
import { AnchorHTMLAttributes, PropsWithChildren } from "react"; | |
type PropTypes = LinkProps & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">; | |
/// A unified component for the next/link <Link> and a standard <a> anchor. | |
/// Will lift href and all other props from Link up to the Link. | |
/// Will automatically make an <a> tag containing the children and pass it remaining props. | |
const LinkTo = ({ | |
children, | |
href, | |
as, | |
replace, | |
scroll, | |
shallow, | |
prefetch, | |
locale, | |
...anchorProps | |
}: PropsWithChildren<PropTypes>) => { | |
return ( | |
// These props are lifted up to the `Link` element. All others are passed to the `<a>` | |
<Link {...{ href, as, replace, scroll, shallow, prefetch, locale }}> | |
{/* eslint-disable-next-line react/jsx-props-no-spreading */} | |
<a {...anchorProps}>{children}</a> | |
</Link> | |
); | |
}; | |
export default LinkTo; |
@adriankwiat What versions of Typescript and Next are you using? And what does your tsconfig
look like? That is strange but I'm guessing it is a strictness check in typescript that is complaining that TECHNICALLY as?: Url
and as: Url | undefined
are different (though functionally they are basically the same).
I see that my VSCode uses dev version of typescript 4.4.0. Changing back to stable 4.3.2 resolved problem. I didn't think about that before
Oof good to know that this might break with 4.4 though
Hi made a similar solution but instead of AnchorHTMLAttributes
I used HTMLAttributes
. Just wanted to thank you for the solution :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@zackdotocomputer ah cool, learned something new. I didn't know about
Omit
and that's definitly a good idea!