Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Event Handlers with TypeScript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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/> 
)} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading