2
votes

I have an ExternalLink component that I use to render anchor tags for external URLs. I've implemented it using styled-components.

CodeSandbox link

ExternalLink.tsx

It basically gets an href prop and render the children as {props.children}.

const LinkAnchor = styled.a``;

interface ExternalLink_I {
  className?: string;
  href: string;
}

const ExternalLink: React.FC<ExternalLink_I> = (props) => {
  console.log("Rendering ExternalLink...");

  return (
    <LinkAnchor
      className={props.className} // ALLOW STYLING WITH STYLED-COMPONENTS
      href={props.href}
      target="_blank"
      rel="noopener noreferrer"
    >
      {props.children}
    </LinkAnchor>
  );
};

But I'm getting an error when rendering this component with children.

App.tsx

export default function App() {
  return (
    <ExternalLink href={"https://www.google.com"}>
      EXTERNAL_LINK
    </ExternalLink>
  );
}

enter image description here

Here is the error msg in text format:

Type '{ children: string; href: string; }' is not assignable to type 'IntrinsicAttributes & ExternalLink_I'.

Property 'children' does not exist on type 'IntrinsicAttributes & ExternalLink_I'.ts(2322)


QUESTION

What am I doing wrong? How can I get rid of this?

2

2 Answers

1
votes

You forgot to mention that the ExternalLink component was wrapped in React.memo. The 'children' prop has been known to cause issues with React.memo, hence removed from the type definitions for the component. Also looking at your code, doesn't seem to be making any big optimisations. Removing it would fix the type error, or you could choose to ignore it.

Here is some light reading regarding this issue:

2
votes

You should add children type too:

interface ExternalLink_I {
  ...
  // or React.element, React.ReactNode etc
  children: string;
}