Home > Mobile >  Property 'target' does not exist on type error using {...props}
Property 'target' does not exist on type error using {...props}

Time:04-07

I'm making a custom link component and passing target="_blank" and rel="noreferrer" as props and using {...props} assigned to the <a>.

const ExternalLinkTwo: React.FC<{
  href: string;
  children: ReactNode;
}> = ({ href, children, ...props }) => (
  <a href={href} {...props}>
    {children}
  </a>
);

export default function App() {
  return (
    <div className="App">
      <ExternalLinkTwo
        href="http://www.google.com"
        target="_blank" //throwing error here, why?
        rel="noreferrer"
      >
        Google 2
      </ExternalLinkTwo>
    </div>
  );
}

Getting this error on the target prop

(JSX attribute) target: string Type '{ children: string; href: string; target: string; rel: string; }' is not assignable to type 'IntrinsicAttributes & { href: string; children: ReactNode; } & { children?: ReactNode; }'. Property 'target' does not exist on type 'IntrinsicAttributes & { href: string; children: ReactNode; } & { children?: ReactNode; }'.ts(2322)

Edit React Typescript (forked)

CodePudding user response:

If your goal is to support the normal set of <a> attributes but make href required, use something like this...

import { AnchorHTMLAttributes } from "react";

interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
  href: string; // make href non-optional
}

const ExternalLinkTwo: React.FC<LinkProps> = ({ href, children, ...props }) => (
  <a href={href} {...props}>
    {children}
  </a>
);

You don't need to include children in your prop type. It's provided automatically via React.FC.

Edit React Typescript (forked)


An alternative is to simply extend Record<string, string> to accept any extra attributes.

interface LinkProps extends Record<string, string> {
  href: string;
}
  • Related