Reactjs allows one-way data binding, meaning passing data down the hierarchy from parent to child. To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive.
If your app has a deeper component tree, consider using the Context API or Redux. Passing data to a distant child component through intermediate components is cumbersome. It is called prop drilling. Check out the below articles to learn more about the Context API and Redux.
Reactjs global state without redux: React state management with context apiSimple Redux store example with React + Hooks
The parent component passes a function as a prop
Here we pass the callback function reference to the child component as a prop. It is important to pass the reference to the function. Not the function callback() which will result in immediate execution of the function.
import { useState } from "react"
import { Child } from "./Child"
export const Parent = () => {
const [name, setName] = useState<string|undefined>()
const callback = (name: string | undefined) => {
setName(name)
}
return(
<>
<div>{name}</div>
<div><Child onClick={callback}/></div>
</>
)
}
The child component calls the parent function to send data to the parent. The child component receives the reference to the parent function as a prop. Then it does a function call with parameters that we want to pass to the parent.
import { useRef } from "react"
export interface ChildProps{
onClick: (name: string|undefined) => void
}
export const Child = (props: ChildProps) => {
const inputName = useRef<HTMLInputElement>(null)
const onButtonPress = () => {
props.onClick(inputName?.current?.value)
}
return(
<>
<input ref={inputName} type="text"/>
<button onClick={onButtonPress}>Callback</button>
</>
)
}