1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I went down the wrong path completely. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.