4

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``

1 Answer 1

16

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip on extending React.HTMLAttributes<HTMLElement>, this is exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.