How to pass data from child component to parent in ReactJS?

Passing data between parent and child using component props is quite standard in ReactJS. It can be the functional or class-based component but the core concepts of passing data from child component to parent component are the same.

The main point here is we need to define a function in the parent component and pass that function as a prop to the child component.

From the child component, we need to call the parent component’s function with the data we want to pass. Following is the code example of passing data between parent and child functional components:

Parent component

import React from 'react';
import Child from './Child'
/*
 * Purpose: The purpose of this component is to exchange data between
 *          Parent and child component.
 *
 * Version: 1.0
 */

const Parent = () =>{
    let userSettings = {};
    const getPreferenceData = (params) => {
        userSettings = {...userSettings, ...params};
        console.log(userSettings);
    };

    return (
        <div>
            <h1>Data exchange</h1>
            <Child sendData={getPreferenceData} />
        </div>

    );
};
export default Parent;

Child component

import React from 'react';
/*
 * Purpose: The purpose of this component is to exchange data between
 *          Parent and child component.
 *
 * Version: 1.0
 */

const Child = (props) =>{
    const handleClick = () => {
        props.sendData({name: 'Joe Smith'});
    };
    return (
        <div>
            <button onClick={handleClick}>Click me</button>
        </div>
    );
};
export default Child;