I have a functional component (written in Typescript) that needs to pass a handler function down to a child component. Here is a scaled down version of the parent function:
type Props = { handleLocationChange(): void };
const Sidebar: React.FC<Props> = (props) => {
const handleLocationChange = () => {
console.log('Location Changed.');
};
return (
<>
<Search handleLocationChange={handleLocationChange} />
</>
)
}
In VS Code the search component shows an error:
Type '{ handleLocationChange: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'handleLocationChange' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)
Any help would be much appreciated. I am sure I am missing something small.
You need to declare the prop type in Search Component and declare type to parameter too:
//use this type to both components (children and parent)
interface FuncProps {
//here you can declare the return type (here is void)
handleLocationChange: (values: any) => void;
}
//children start
// here are the tip, define the type in the React.FC and in the FC's parameters itself
const Search: React.FC<FuncProps> = (props: FuncProps) => {
... your component behavior and view ...
return (
{/*↓↓↓↓ use the prop like this ↓↓↓↓*/}
<input onClick={props.handleLocationChange('something if you need')}/>
)
};
//children end
// parent start
const Sidebar: React.FC<Props> = (props: FuncProps) => {
return (
<>
<Search handleLocationChange={props.handleLocationChange} />
</>
)
}
//parent end
I hope this answer can help who wants to use typescript and want to easy your own life passing functions through components (I don't recomend pass functions through many levels).
You need to declare handleLocationChange as a prop on the Search component
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