Callback function in React JS

In this article, we will teach you how you can use a callback function to be called from child parent that will invoke a function in parent component in React JS.

Let’s say you have:

  • A parent component that has an array.
  • You are looping through an array and displaying the data using child component.
  • You want to call a function from child component that will invoke a function in parent component.
<html>
    <head>
        <script src="js/babel.min.js"></script>
        <script src="js/react.development.js"></script>
        <script src="js/react-dom.development.js"></script>

        <script type="text/babel" src="js/SingleData.js"></script>
    </head>

    <body>
        <div id="app"></div>

        <script type="text/babel">
            function App() {

                const [data, setData] = React.useState([{
                    id: 1,
                    name: "Adnan",
                    age: 31
                }, {
                    id: 2,
                    name: "Afzal",
                    age: 65
                }, {
                    id: 3,
                    name: "Ali",
                    age: 43
                }]);

                return (
                    <>
                        { data.map(function (d, index) {
                            return (
                                <SingleData key={ `data-${ d.id }` }
                                    d={ d } />
                            );
                        }) }
                    </>
                );
            }

            ReactDOM.createRoot(
                document.getElementById("app")
            ).render(<App />);
        </script>
    </body>
</html>

Here, we have a React parent component that has an array of data. Each array element has an ID, name and age. You might be receiving this data from API. In each loop iteration, it is rendering a child component.

  • key: This is used by React JS to uniquely identify an element.
  • d: This is the property value parent component is sending to the child component.

What are props in React JS ?

props (properties): Props are used in React JS to pass the data from parent component to child component. They are read-only so child component cannot modify the value of “d”.

Our child component will look like this:

// js/SingleData.js

function SingleData({ d }) {
    return (
        <div>
            <p>
                { d.id } - { d.name } { d.age }
            </p>
        </div>
    );
}

Callback function

Now, let’s assume you want to have a delete function in child component that, when called, will call a function in parent component. So that the parent component that perform an action on that child. In this case, we will remove that array element from “data” array in parent component.

So first, we will create a delete button in child parent. Once that button is clicked, we will call a function we will receive in props from parent component.

// js/SingleData.js

function SingleData({ d, onDelete }) {
    return (
        <div>
            <p>
                { d.id } - { d.name } { d.age }
            </p>

            <button type="button"
                onClick={ function () {
                    onDelete(d.id);
                } }>Delete</button>
        </div>
    );
}

Now, in our parent component, we need to pass this function as an argument to the child component.

<SingleData key={ `data-${ d.id }` }
    d={ d }
    onDelete={ onDelete } />

Finally, we will create that function in parent component that will search the array element using ID and remove it from array. At the end, we will update the React state variable as well.

function onDelete(id) {
    const tempArr = [ ...data ];
    for (let a = 0; a < tempArr.length; a++) {
        if (tempArr[a].id == id) {
            tempArr.splice(a, 1);
            break;
        }
    }

    setData(tempArr);
}

Here is the complete code of this tutorial.

Parent component

<html>
    <head>
        <script src="js/babel.min.js"></script>
        <script src="js/react.development.js"></script>
        <script src="js/react-dom.development.js"></script>

        <script type="text/babel" src="js/SingleData.js"></script>
    </head>

    <body>
        <div id="app"></div>

        <script type="text/babel">
            function App() {

                const [data, setData] = React.useState([{
                    id: 1,
                    name: "Adnan",
                    age: 31
                }, {
                    id: 2,
                    name: "Afzal",
                    age: 65
                }, {
                    id: 3,
                    name: "Ali",
                    age: 43
                }]);

                function onDelete(id) {
                    const tempArr = [ ...data ];
                    for (let a = 0; a < tempArr.length; a++) {
                        if (tempArr[a].id == id) {
                            tempArr.splice(a, 1);
                            break;
                        }
                    }

                    setData(tempArr);
                }

                return (
                    <>
                        { data.map(function (d, index) {
                            return (
                                <SingleData key={ `data-${ d.id }` }
                                    d={ d }
                                    onDelete={ onDelete } />
                            );
                        }) }
                    </>
                );
            }

            ReactDOM.createRoot(
                document.getElementById("app")
            ).render(<App />);
        </script>
    </body>
</html>

Child component

function SingleData({ d, onDelete }) {
    return (
        <div>
            <p>
                { d.id } - { d.name } { d.age }
            </p>

            <button type="button"
                onClick={ function () {
                    onDelete(d.id);
                } }>Delete</button>
        </div>
    );
}

We used this method in one of our project “Multi-purpose platform in Node JS and Mongo DB“. You can check this out if you want to get a practically view of it.

That is how you can use a callback function in React JS that will invoke a function from child component to parent component.