Home > Software design >  Passing a function as a prop to child won't run function when clicked
Passing a function as a prop to child won't run function when clicked

Time:12-31

In my App component I have a function that is passed as prop to a child component. In this child component I have a button that has an onClick that is set to run this function from props but when I click the button it does not run. Not sure what I am missing here thanks.

App.jsx

  function addGoalBtnClick() {
    console.log("Yep")
  }

  return (
    <div className="App">
      <AddGoalBtn addGoalBtnfunc={addGoalBtnClick} />
    </div>
  );

Child Component

function AddGoalBtn(props) {
  console.log(props)

  return (
    <div className="add-goal-btn-wrapper">
      <button onClick={props.AddGoalBtnfunc} className="add-goal-btn">
        <FontAwesomeIcon icon={faPlus} size="2x" color="white" />
      </button>
    </div>
  );
}

CodePudding user response:

The problem is with the capitalization of the prop you pass.

You pass it as addGoalBtnfunc (first letter is a), but you use it in the component as props.AddGoalBtnfunc (first letter is A), so since it is not found in the props it is undefined.

CodePudding user response:

You have made a mistake in your child component by capitalizing the addGoalBtnfunc, inside your parent it is not capitalized. Changing this should fix the issue.

  • Related