Skip to content

Support for onClick for the Link component #16

@TimurKr

Description

@TimurKr

Hi! From what I understand, the <Link /> component simply ads an onClick property to the default Link. But this gets overwritten if we manually set onClick on it, essentially making it useless. I will make a PR to fix this.

/**
 * A custom Link component that wraps Next.js's next/link component.
 */
export function Link({
    href,
    children,
    replace,
    scroll,
    ...rest
}: Parameters<typeof NextLink>[0]) {
    const router = useRouter();
    const startProgress = useProgress()

    return (
        <NextLink
            href={href}
            onClick={(e) => {
                if (isModifiedEvent(e)) return;
                e.preventDefault();
                startTransition(() => {
                    startProgress()
                    const url = typeof href === 'string' ? href : formatUrl(href)
                    if (replace) {
                        router.replace(url, { scroll })
                    } else {
                        router.push(url, { scroll })
                    }
                })
            }}
            {...rest} // Here if rest includes `onClick`, it overwrites the functionality
        >
            {children}
        </NextLink>
    );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions