Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript issue with onClick with styled-components

I'm using a custom Icon component like so:

<Icon onClick={() => {}} />

However, TypeScript underlines the Icon and gives the following message, which I can't quite figure out:

Property 'onClick' does not exist on type 'IntrinsicAttributes & Pick<Pick<Props, "className" | "name"> & Partial<Pick<Props, never>>, "className" | "name"> & { theme?: any; } & { as?: "symbol" | "object" | ... 174 more ... | undefined; }'.ts(2322)

My Icon component is a styled-component as seen below:

interface Props {
  name: string
  className?: string
}

const Icon = styled(({name, className, ...props}: Props) => <i className={`material-icons ${className}`} {...props}>{name}</i>)``

I was able to silence TypeScript by adding the following to Icon's interface declaration to allow any property:

[x: string]: any

but it feels like it's a hack, and I'd like to understand the issue and find a proper solution.

Interestingly, if I use the same way a custom Button component, I don't get the error:

<Button onClick={() => {}} />

const Button = styled.button``
like image 782
artooras Avatar asked Sep 05 '25 16:09

artooras


1 Answers

Your prop definition for Icon tells typescript, that only name and className are valid properties.

interface Props {
  name: string
  className?: string
}

If you also want allow onClick you have to add it:

interface Props {
  name: string;
  className?: string;
  onClick: (e: Event) => void;
}

or if you want to allow all properties, which are valid for <i> you use the following:

interface Props extends React.HTMLAttributes<HTMLElement> {
  name: string
}
like image 104
ChrisG Avatar answered Sep 09 '25 02:09

ChrisG