I am passing an onClick function as a prop in my react app from one component to another. It gives an error which shows as Uncaught TypeError: handleOnClick is not a function
. Here is my function which i am passing through,
propList = ['a', 'b', 'c']
const handleOnClick = (propArr: any) => {
console.log('propArr===>', propArr)
}
<ChildComponent handleOnClick ={handleOnClick } propList={propList}/>
Here is the component which takes those props,
export const ChildComponent = (propList: any, handleOnClick : any) => {
const handleSubmit = () => {
handleOnClick ('pass this to parent!')
}
return(
<button onClick={handleSubmit}>Submit</button>
)
}
Do i need to change something specifically to overcome this situation?
>Solution :
This is incorrect:
export const ChildComponent = (propList: any, handleOnClick : any) => {
// ...
};
Components take props as a single parameter which is an object. So at a minimum that should be:
export const ChildComponent = ({ propList, handleOnClick } : any) => {
// ...
};
That uses destructuring in the parameter list to pick the propList
and handleOnClick
properties from the first parameter’s value.
But there’s no point in using TypeScript if you’re just going to use the any
type. Better to properly define a typed props interface for the component, and use that. For instance:
type ChildComponentProps = {
propList: AppropriateTypeHere[];
handleOnClick(propArr: AnotherAppropriateTypeHere[]): void;
}
export const ChildComponent = ({ propList, handleOnClick } : ChildComponentProps) => {
// ...
};