To pass data between components, we often use the prop. Passing a Function as props in React is the same thing. The article will show you two ways that are passing functions between parent components to child components and vice versa.
Pass a Function as props in React
Passing a function from parent to child
To do that, we need to create a handler function in the parent component, then pass the function as a prop to the child component.
Follow the example below:
import React from "react"; const Child = ({ handleClick }) => { return <button onClick={handleClick}>Click</button>; }; const App = () => { const handleClick = () => { console.log("This is the parent"); }; return <Child handleClick={handleClick} />; }; export default App;
In this example, we will use the App component as a parent and create a button click in the Child component.
handleClick
: function acts as a handler and is passed down to the Child element via the handleClick
property. The Child component will receive this function and immediately assign it as the click event handler. So when we click on the button, we will get the log “This is the parent”.
Output:

Pass a function from child to parent
So how do we pass a function from the child to the parent component? We will change the above example a bit.
Still has the handleClick
function, but now it will take a callback as an argument. Then pass this function to the child component as a prop.
const App = () => { const handleClick = (callback) => { // Here, you have the function from the child. callback(); }; return <Child handleClick={handleClick} />; };
Now in the child component, create a function called message.
const Child = ({ handleClick }) => { const message = () => { console.log("From child function"); }; return ( <button onClick={() => handleClick(message)}>Click</button> ); };
This message function will be the argument to the handleClick
function received in the parent component. Now it acts as a callback.
Here is the entire code:
import React from "react"; const Child = ({ handleClick }) => { const message = () => { console.log("From child function"); }; return ( <button onClick={() => handleClick(message)}>Click</button> ); }; const App = () => { const handleClick = (callback) => { // Here, you have the function from the child. callback(); }; return <Child handleClick={handleClick} />; }; export default App;
Output:

Summarry
In short, with several steps which mentioned in the article, you can pass a Function as props in React in an easy way. But if you have too many props to pass, then you should use libraries to manage this like Redux.
If you have any questions, please leave a comment below.

After studying and researching, I have acquired the necessary programming skills of a web programmer. In addition to HTML, Css, Bootstrap has some popular libraries such as reactJS and NodeJS. It is enough for me when designing from front-end to back-end.