I've tried to use "Link" element as my custom react component that I modified it with typescript to add some more facilities but everytime used it in my project it's made me to write a property with the name of props which its included some other properties :
below line is my typescript runtime error :
Type '{ link: string; title: string; }' is missing the following properties from type 'DetailedReactHTMLElement<{ onm ouseEnter?: MouseEventHandler<Element> | undefined; onClick?: MouseEventHandler<Element> | undefined; href?: string | undefined; ref?: any; }, HTMLElement>': type, ref, props, keyts(2739)
I wrote my custom react component :
import style from "./Button.module.css";
import Link from "next/link";
export const Button: React.FunctionComponent<
React.DetailedReactHTMLElement<
{
onm ouseEnter?: React.MouseEventHandler<Element> | undefined;
onClick?: React.MouseEventHandler;
href?: string | undefined;
ref?: any;
},
HTMLElement
> & {
title?: string;
link?: string;
}
> = ({ title, children, link, ...rest }) => (
<Link href={`${link}`} {...rest}>
{title ?? children}
</Link>
);
when I using it somewhere as my Button :
<Button link={exploreLink} title="Explore Event" />
CodePudding user response:
Your accepted answer isn't the correct usage of Next/link.
A few points to note so you know what's going on...
- Your losing all Next/link attributes (as, shallow, passHref, replace, etc.)
- You are missing the required anchor tag inside of next/link
- Next link has its own type
link
as a prop name is confusing as the standard ishref
and it's already includedLinkProps
hold all standard next/link props;FC
is react's built in functional component - addschildren
prop and sets return to a JSX/React nodeHTMLProps
are react's built in synthetic events and react specific propsHTMLAnchorElement
adds all standard html props like className, title, etc.
import NextLink, { LinkProps } from 'next/link';
import { HTMLProps, FC } from 'react';
const LinkButton: FC<LinkProps & HTMLProps<HTMLAnchorElement>> = ({
as, children, href, replace, scroll, shallow, passHref, ...rest
}) => (
<NextLink
as={as}
href={href}
passHref={passHref}
replace={replace}
scroll={scroll}
shallow={shallow}
>
<a {...rest}>
{children}
</a>
</NextLink>
);
If your adding custom props you could make your own type
type MyLink = {
customProp?: string;
} & LinkProps & HTMLProps<HTMLAnchorElement>;
LinkButton: FC<MyLink> = ()...
Usage
<LinkButton href={exploreLink} title="Explore Event" />
CodePudding user response:
You don't need React.DetailedReactHTMLElement; try:
React.FunctionComponent<
{
onm ouseEnter?: React.MouseEventHandler<Element>;
onClick?: React.MouseEventHandler;
href?: string;
ref?: any;
}
& {
title?: string;
link?: string;
}
>