Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a prop to a Typescript React Functional Component

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.

like image 527
Josh Scott Avatar asked Dec 23 '22 20:12

Josh Scott


2 Answers

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).

like image 87
Danrley Pereira Avatar answered Dec 26 '22 00:12

Danrley Pereira


You need to declare handleLocationChange as a prop on the Search component

like image 40
Daniel Duong Avatar answered Dec 25 '22 22:12

Daniel Duong