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

Viewed 302

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;
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) => {
Related