How to call a function from Props interface in Typescript/React

Viewed 1288

I'm trying to update the state of a parent component from the child. I've passed down a function in the Props interfact, but I can't seem to call it using my clickHandler.

There's user info in the parent component which should update from various small components that comprise a registration.

Does this seem to be the right approach?

App.tsx

  const updateName = (
        e: React.MouseEvent,     // Function to update parent state
        firstName: string,       // Triggered by child components
        lastName: string
    ) => {
        setFirstName(firstName);
        setLastName(lastName);
    };

Component render with this function as prop:

  <FullName
      firstName={""}
      lastName={""}
      updateName={(e, first: string, last: string) =>
          updateName(e, first, last)
      }
  />;

inside ChildComponent.tsx

This is the props interface:

interface NameProps {
    firstName: string;
    lastName: string;
    updateName: (e: React.MouseEvent, first: string, last: string) => void;
}

This is where I want to call the function, in order to send the state data from the child, to the parent as an argument in updateName!

    function handleClick(e: React.FormEvent<HTMLButtonElement>) {
        console.log(first, last);

        // I want to call NameProps.updateName here

    }

Please let me know if this is totally the wrong approach, but it seems I'm very close.

1 Answers

So what stops you from calling the updateName() from child? Can you paste your child component's code? Is it a class or functional component?

I do this like this:

In Parent:

const Parent = () => {
  const myFunction = function (someArgument) {
    // do stuff
  }

  return (
  <div>
    <Child stringParameter="foo" myFunction={myFunction}/>
  </div>
  );
};

In child:

const Child = ( { stringParameter, myFunction} ) => {
  myFunction(stringParameter);

  return (
    <div>lorem ipsum</div>
  );
};

I've made it as simple as possible so I hope this answers your question (no interface etc.). Of course props deconstruction also for readability.

Related