Home > OS >  React and TypeScript: How to pass Arguments to Event handler of type: MouseEventHandler
React and TypeScript: How to pass Arguments to Event handler of type: MouseEventHandler

Time:03-24

How do I define the event handler: handleStatus of the type: MouseEventHandler so that I can pass an additional argument of the type: Todo to the function?

interface TodoProps {
    
    todos: Array<Todos>
    
    handleStatus: MouseEventHandler,
    index: number,
    className: string

}

export const Todo: FunctionComponent<TodoProps> = ({ todos, handleDeleteTodo, handleStatus, index, className }): ReactElement => {

   
    const d_todo: Todos = todos[index];
    

    return(
        <> 
            <div className= { className } key={ todos[index].id.toString() }>
                {todos[index].describtion}
                <Button lable='' disabled= { false } onClick= { () => handleStatus(todos[index])  }  />

            </div>
        </>
    );
}

I got the Error:

ERROR in src/components/Todo.tsx:29:84
TS2345: Argument of type 'Todos' is not assignable to parameter of type 'MouseEvent<Element, MouseEvent>'.
  Type 'Todos' is missing the following properties from type 'MouseEvent<Element, MouseEvent>': altKey, button, buttons, clientX, and 29 more.
    27 |             <div className= { className } key={ todos[index].id.toString() }>
    28 |                 {todos[index].describtion}
  > 29 |                 <Button lable='' disabled= { false } onClick= { () => handleStatus(todos[index])  }  />
       |                                                                                    ^^^^^^^^^^^^
    30 |                 
    31 |             </div>
    32 |         </>

CodePudding user response:

If you need to pass both event MouseEvent and both Todo then you need to declare handleStatus as a function that accept an event and a Todo:

handleStatus: (event: MouseEvent, todo: Todo) => void

then in the component:

onClick={(event) => handleStatus(event, todos[index])}

  • Related