React Mastery / React Basics

Methods as props

✅ What does it mean?

  • In React, you can pass a function (method) from a parent component to a child component as a prop.

  • This allows the child component to communicate back with the parent or trigger some action in the parent.


🧠 Why use it?

  • React follows one-way data flow (parent → child).

  • But if a child needs to notify the parent (like "button was clicked" or "form was submitted"), you pass a method as a prop to do that.


🔹 Key Points

  • A method is just a JavaScript function.

  • You pass it to the child component like any other prop.

  • In the child, you call it using props.methodName() (or this.props.methodName() if it’s a class component).


👩‍🏫 Real-world Example

Imagine a parent component has a counter, and a child component has a button.

  • The child can’t directly update the parent’s state.

  • So the parent passes a method like handleIncrement to the child.

  • The child calls that method when its button is clicked — and the parent handles the logic.


🔹 Parent.jsx

What happens here:

  1. The parent component uses useState to create a state variable called count with an initial value of 0.

  2. It defines a method handleIncrement() that increases the count by 1 using setCount().

  3. It renders:

    • A heading and the current value of count

    • The Child component, and passes the method handleIncrement to it as a prop named onButtonClick.

✅ Key idea: The parent owns the state and the method to change it. The child just calls it.


🔹 Child.jsx

What happens here:

  1. This is a simple functional component that receives props.

  2. It renders:

    • A heading

    • A button that calls props.onButtonClick when clicked

✅ Key idea: The child doesn't know anything about the count. It just executes a method sent from the parent.


🔁 Flow of Execution (when user clicks button):

  1. You click the button in the Child component.

  2. props.onButtonClick() is called — this actually refers to the handleIncrement() function from the Parent.

  3. handleIncrement() runs in the parent and updates the state using setCount().

  4. The parent re-renders, and the updated count is shown.