Home > Enterprise >  Unable to pass a function as a prop to child component in React
Unable to pass a function as a prop to child component in React

Time:10-27

I'm trying to pass a function (addTask) as a prop from parent component (MainComponent.js) to Child Component (Button.js) but it's not working. I've also passed a variable (btnColor) as prop and it's working properly. What am I missing?

MainComponent.js:

import Button from "./Button";

const MainComponent = () => {
  
  const addTask = () => {
    console.log("Task Added...");
  };

  return (
    <div>
      <div> Header Component here </div>
      <div> Some Data </div>
      <Button onClick={addTask} btnColor="red" />
      <div> Footer Component here </div>
    </div>
  );
};

export default MainComponent;

Button.js:

const Button = ({ addTask, btnColor }) => {
  return (
    <button style={{ backgroundColor: btnColor }} onClick={addTask}>
      Add
    </button>
  );
};

export default Button;

I'm expecting the console to log 'Task Added...' but it isn't logging anything.

CodePudding user response:

You're not passing it through correctly. You're passing it to onClick whereas you want to pass it through as addTask

Incorrect: <Button onClick={addTask} btnColor="red" />

Correct: <Button addTask={addTask} btnColor="red" />

CodePudding user response:

I think it should be like this

    const MainComponent = () => {
    
        const addTask = () => {
            console.log('Added new task...')
        }
    
        return (
            <Button addTask={addTask} />
        )
    }
    
    const Button = ({ addTask }) => {
        
        return (
            <button onClick={addTask} ></button>
        )
    }
  • Related