DEV Community

Ayako yk
Ayako yk

Posted on

Passing Functions As Props In React

While working on refactoring code, I realized that I didn't fully understand callbacks. So, today's article is fundamental, but I decided to document this as part of my learning journey.

Passing Props
As the documentation states:

React components use props to communicate with each other. Every parent component can pass information to its child components by giving them props.

Passing a Function from Parent to Child
This is a fundamental method of passing props from a parent component to a child component.

When clicking the "Click" button in the child component, it invokes the handleClick function passed from the parent component.

Parent.tsx

import Child from "./Child"

const Parent = () => {
  const handleClick = () => {
    console.log("button clicked")
  }

  return <Child handleClick={handleClick} />
}

export default Parent
Enter fullscreen mode Exit fullscreen mode

Child.tsx

import { FC } from "react"

type ChildProps = {
  handleClick: () => void
}

const Child: FC<ChildProps> = ({ handleClick }) => {
  return (
    <div>
      <button onClick={handleClick}>Click</button>
    </div>
  )
}

export default Child
Enter fullscreen mode Exit fullscreen mode

Passing a Function from Child to Parent
In this case, both the button and the function that logs "button clicked" reside in the child component, but the parent component renders the child component. Therefore, we need to "send" the function to its parent. We pass the callback as an argument to the handleClick function, and the handleClick function executes the callback() in the parent component.

Parent.tsx

import Child from "./Child"

const Parent = () => {
  const handleClick = (callback: () => void) => {
    callback()
  }

  return (
    <div>
      <Child handleClick={handleClick} />
    </div>
  )
}

export default Parent
Enter fullscreen mode Exit fullscreen mode

Child.tsx

import { FC } from "react"

type ChildProps = {
  handleClick: (callback: () => void) => void
}

const Child: FC<ChildProps> = ({ handleClick }) => {
  const callback = () => {
    console.log("button clicked")
  }
  return (
    <div>
      <button onClick={() => handleClick(callback)}>Click</button>
    </div>
  )
}

export default Child
Enter fullscreen mode Exit fullscreen mode

As projects grow larger and more complex, or when useContext is used, I tend to lose track of the flow and struggle to create components. I will continue learning about these concepts.

Top comments (0)