0

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.

2 Answers 2

3

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" />

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

Comments

2

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>
        )
    }

Comments

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.