Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass function from parent component to child component with type assingable

I'm new to TypeScript and I want to pass my function onDogSelected to the children component <Dogs />.

When I tried, I got some error message like this:

Type '{ onDogSelected: (e: any) => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.Property 'onDogSelected' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

I don't know what this means. I was trying to figure it out but still have no solution.

const HomePage: React.FC = () => {
    const [dogSelected, setDogSelected] = useState("");
    const onDogSelected = (e: any) => {
        setDogSelected(e.target.value)
    }
    return (
        <ApolloProvider client={client2}>
          <Dogs onDogSelected={onDogSelected} />
          {dogSelected && <span>{dogSelected}</span>}
        </ApolloProvider>
    );
};

export default HomePage;
like image 254
Erwin Ramadhan Avatar asked Mar 27 '26 19:03

Erwin Ramadhan


1 Answers

React.FC is deprecated, you should use React.FunctionComponent.

React.FunctionComponent is a generic type. You should pass your component's props into it if you're expecting anymore.

So the Dogs component should look like,

import { FunctionComponent } from "react";

const Dogs: FunctionComponent<DogsProps> = (props) => {
  ...
};

interface DogsProps {
  onDogSelected(e: any): void;
}

You don't have to create an interface or type, you can just pass it as an argument

const Dogs: FunctionComponent<{ onDogSelected(e: any): void; }> = (props) => {
like image 178
a.mola Avatar answered Apr 02 '26 22:04

a.mola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!