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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With