Passing a function prop from child to parent

Posted on

in

,

Using the same example as passing a function from parent to child but going in the opposite direction.

const ChildBtn = ({ handleChild, consoleString, btnText }) => {
    const childFunction = () => {
        console.log(consoleString || "default console text");
      };

    return <button onClick={() => handleChild(childFunction)}>{btnText || "default btn text"}</button>;
  };

  const Parent = (props) => {
    const callBackChild = (callback) => {
        callback();
    }

    return <div><ChildBtn handleChild={callBackChild} btnText={props.btnText} consoleString={props.consoleString} /></div>;
  };

Here the parent has a callback function and passes it to the child component. The child calls the callback with it’s own function as the argument. As before you can use the component like so:

<Parent consoleString={"string here"} btnText={"apply"} />

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031