Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & Typescript how get onClick prop from child to parent

I'm using react & typescript.

I wonder how i can pass event from parent to child with props.

so is example

parent.tsx

const ParentComponent: React.FC<ParentProps> = (props) =>  {
   const [activeItem, setActiveItem] = useState("");

   const getActiveItem = (e: React.MouseEvent, title: string) => {
      setActiveItem(title)
   };

   return (
      <ChildComponent activeItem={activeItem} clickHandler={(e) => getActiveItem(e, 'TITLE')} /> 
   )
}

child.tsx

interface ChildProps {
  activeItem: string;
  clickHandler: () => any;
}


const ChildComponent: React.FC<ChildProps> = (props) =>  {
   return (
      <button onClick={props.clickHandler} /> {props.activeItem} </button>
   )
}

and on parent component i'm getting error on clickHandler:

Type '(e: any) => void' is not assignable to type '() => void'.ts(2322)
like image 580
ciz30 Avatar asked Oct 14 '25 04:10

ciz30


1 Answers

This is how the typings for the click handler should be:

interface ChildProps {
  activeItem: string;
  clickHandler: (e:  React.MouseEvent<HTMLButtonElement>) => void;
}

You should not use any as the type for the parameter, as on click event handler accepts Event as the parameter.

like image 145
wentjun Avatar answered Oct 16 '25 18:10

wentjun