Search code examples
javascriptreact-typescript

Passing event handler as props in React Typescirpt


I'm trying to pass an event handler from a parent component to a child. the point is to change the state of the parent when user clicks on child component. the problem is it throws an error as below:

 /*
    (property) onClick: React.MouseEventHandler<Element>
     Type '{ onClick: MouseEventHandler<Element>; }' is not assignable to type 'IntrinsicAttributes & Props'.
     Property 'onClick' does not exist on type 'IntrinsicAttributes & Props'
 */

the Parent Component:

export default function Card(): JSX.Element {
  const [clear, setClear] = useState<boolean>(false);

  const handleClick:React.MouseEventHandler = (): void => {
    setClear(!clear);
  };

  return (
    <Wrapper>
      <Title>5 birthdays today</Title>
      {clear ? "" : list}
      <Button onClick={handleClick} />
    </Wrapper>
  );
}

The child:

interface Props {
  handleClick: React.MouseEventHandler<Element>;
}

export default function Button({ handleClick }: Props): JSX.Element {
  return <Btn onClick={handleClick}>Clear All</Btn>;
}

I did looked up for the solution in the React Typescript stylesheet

but didn't find the answer.


Solution

  • This message gives You the hint:

    Property 'onClick' does not exist on type 'IntrinsicAttributes & Props'

    You need to add the proper type to the child prop types. Try this

    interface Props {
        onClick: React.MouseEventHandler<HTMLButtonElement
    }
    

    You need to inform TS that Your child component expects the onCLick prop. In Your case TS is waiting for the handleClick prop which is incorrect because the props name is "onCLick"