MeltingDog
MeltingDog

Reputation: 15404

How to fix 'element implicitly has an 'any' type. TS7031' for function?

I am new to react am getting the error

Binding element 'onClick' implicitly has an 'any' type. TS7031

On the following code

const CloseButton = ({ onClick }) => {
  const classes = useStyles();
  return <CloseIcon className={classes.closeButtonStyles} onClick={onClick} />;
};

I know I need to define a type but I don't know which for an onClick function. Google is not giving me any help.

Would anyone know what type I am meant to use?

Upvotes: 5

Views: 2677

Answers (1)

brietsparks
brietsparks

Reputation: 5006

It depends on what CloseIcon's onClick prop expects. Many native HTML elements will accept a React MouseEventHandler for onClick.

For example:

import React, { MouseEventHandler } from 'react';

function MyComponent({ onClick }: { onClick: MouseEventHandler }) {
  return (
    <button onClick={onClick}>Button</button>
  );
}

So you can try:

import { MouseEventHandler } from 'react';


const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => {
  const classes = useStyles();
  return <CloseIcon className={classes.closeButtonStyles} onClick={onClick} />;
};

Upvotes: 6

Related Questions