Handling function callbacks in TypeScript and React

Mike Cole :

In my React app using TypeScript, I'm trying to have a child object call a function in the parent. I'm having some issues getting the typings right. Here's a trimmed down example:

function RequestVisitAddress(onAddressSelected: (address: GoogleAddressParser) => void) {
  const [selectedAddress, setSelectedAddress] = useState<GoogleAddressParser | null>(null);

  const onSubmit = () => {
    onAddressSelected(selectedAddress as GoogleAddressParser);
  };

  return (
    <Button onClick={onSubmit} />
  );
}
function Parent() {
  const onAddressSelected = (address: GoogleAddressParser) => {
    console.log(address);
  };

  return (
    <RequestVisitAddress onAddressSelected={onAddressSelected} />
  );
}

When the button is clicked in the RequestVisitAddress component, I would like to run the onAddressSelected method in Parent. However, I'm getting the following warning on the onAddressSelected attribute in the Parent component:

Type '{ onAddressSelected: (address: GoogleAddressParser) => void; }' is not assignable to type 'IntrinsicAttributes & ((address: GoogleAddressParser) => void)'.
  Property 'onAddressSelected' does not exist on type 'IntrinsicAttributes & ((address: GoogleAddressParser) => void)'.ts(2322)

What do I need to adjust to make this work?

JeromeBu :

The problem is that RequestVisitAddress props are not correctly typed. This is what you are looking for :

type Props = {
  onAddressSelected: (address: GoogleAddressParser) => void,
}

function RequestVisitAddress({onAddressSelected}: Props) {
  const [selectedAddress, setSelectedAddress] = useState<GoogleAddressParser | null>(null);

  const onSubmit = () => {
    onAddressSelected(selectedAddress as GoogleAddressParser);
  };

  return (
    <Button onClick={onSubmit} />
  );
}

You get all your props in an Object, so you need to destructure onAddressSelected from the props to be able to access it.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=391301&siteId=1