Home > Net >  React Event Handlers with TypeScript
React Event Handlers with TypeScript

Time:09-08

I am trying to pass a delete function as props to a child component. When a button is clicked in the child component, an id should be passed as an argument. I couldn't figure out the type for this function. Please see the code below:

const App: React.FC = () => {
  
  const deleteHandle = (id: string) => {
          dispatch(deleteItem(id));
  };

  return (
  <ChildComponent deleteHandle={deleteHandle}/>
  )
}

Child Component:

interface ChildProps {
  deleteHandle: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

const ChildComponent = ({deleteHandle}: ChildProps) => {

  return (
<button onClick={deleteHandle('id')} >Delete<button/> 
 
)} 

deleteHandle should be both a React.MouseEvent and has id type string. How should I write this?

CodePudding user response:

You can update your deleteHandle to take in two arguments, this way you will be able to both have access to the event and any argument you want.

const App: React.FC = () => {
  const deleteHandle = (e: React.MouseEvent<HTMLButtonElement>, id: string) => {
    dispatch(deleteItem(id));
  };

  return (
    <ChildComponent deleteHandle={deleteHandle}/>
  )
}


interface ChildProps {
  deleteHandle: (event: React.MouseEvent<HTMLButtonElement>, id: string) => void;
}

const ChildComponent = ({deleteHandle}: ChildProps) => {

  return (
    <button onClick={e => deleteHandle(e, 'id')} >Delete<button/> 
)} 
  • Related