Home > Back-end >  Prop TypeScript Error With React Component, Using Styled-Components
Prop TypeScript Error With React Component, Using Styled-Components

Time:10-05

I'm creating a Link component that has an option to change color to gray, using the disabled prop. When I hover over {({ disabled }, TypeScript is giving me a Property 'disabled' does not exist on type 'Pick<DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement> error.

Syntax looks correct, not sure what I'm missing here.

const StyledLink = styled.a`

  color: blue;

  ${({ disabled }) => 
    disabled &&
    css`
      color: gray;
    `}
`;


export type TextLinkProps = {
  /**
   * text to be passed in as a link
   */
  link: string;
  /**
   * text to be rendered in the component.
   */
  children: React.ReactNode;
  /**
   * If `true`, color will be gray.
   */
  disabled?: boolean;
};

export function TextLink({ children, link, disabled = false }: TextLinkProps) {
  return (
    <StyledLink href={link} disabled={disabled}> 
      {children}
    </StyledLink>
  );
}

CodePudding user response:

You should specify the props types you get in your styled component, as such:

const StyledLink = styled.a<{ disabled?: boolean }>``

Also just noticed, you can simplify you styles to omit css:

${({ disabled }) => disabled && "color: gray"};

CodePudding user response:

TypeScript is right: anchor elements don't have attribute disabled.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

  • Related