Home > Back-end >  Passing function to child component MouseEventHandler is not assignable to type
Passing function to child component MouseEventHandler is not assignable to type

Time:07-09

I have a React component where I want to pass an event handler from parent to child.

const Cards = () => {
 const hideCard = (cardId) => {
    console.log(`card ${cardId} should be hidden`);
 };

 return (
    <>
        <ChildCard
          hideCard={() => hideCard(card.id)}
         />
    </>
 )
}

interface ChildCardProps {
   hideCard: (cardId: number) => void;
}

const ChildCard = ({hideCard}: ChildCardProps) => {
      return (
         <>
             <button
                onClick={hideCard}
                type="button">Hide this card
             </button>
         </>
      )
}

My editor gives the follow TypeScript warning: Type '(e: MouseEventHandler<HTMLButtonElement>, cardId: number) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>

Is my Type declaration of the return type void incorrect? how do I properly type this?

CodePudding user response:

In the interface of ChildCardProps you are telling TS that hideCard will be a function that will take one parameter cardID which will of type number and It will return nothing.

hideCard: (cardId: number) => void;

but the function that you are passing is not respecting this type.

You are passing a function that is not passing a cardId of type number

hideCard={() => hideCard(card.id)}

So you can declare this function as:

interface ChildCardProps {
  hideCard: () => void;  // REMEMBER THERE IS NO PARAMETER
}

CodePudding user response:

you don't have to override the onClick attribute of the button. you can redefine ChildCardProps

check out the sandbox

  • Related