Home > front end >  How to pass function from parent component to child component with type assingable
How to pass function from parent component to child component with type assingable

Time:09-22

I new at typescript, i want to pass my function onDogSelected to the children component <Dogs />

But 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; }'. idon't know whats meaning i was try to figure it out but still have no solution. Thankyou verymuch for your helping.

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;

CodePudding user response:

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