Blog>
Snippets

Using Callback Functions to Communicate Upwards

Use a callback function passed as a prop to allow a child component to send data back up to its parent.
class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { childData: null };
    }

    // This function will be used as a callback to receive data
    handleChildData = (data) => {
        this.setState({ childData: data });
    }

    render() {
        return (
            <div>
                <ChildComponent onChildDataChange={this.handleChildData} />
                {this.state.childData && <p>Received data from child: {this.state.childData}</p>}
            </div>
        );
    }
}
This code represents a parent component in a React application. It includes a method 'handleChildData' that serves as a callback function for the child component to send data back to the parent component. The 'ChildComponent' is rendered with a prop 'onChildDataChange' that expects a callback function, which is provided by the parent component. When executed, the callback updates the parent's state with the child's data, which can then be used in the parent's render method.
const ChildComponent = ({ onChildDataChange }) => {
    const sendDataToParent = () => {
        const data = 'Data from child'; // Replace with real data logic
        onChildDataChange(data);
    }

    return (
        <div>
            <button onClick={sendDataToParent}>Send Data to Parent</button>
        </div>
    );
};
This code represents a child component that takes a prop 'onChildDataChange', which is a callback function passed from the parent component. Inside the child component, there is a function 'sendDataToParent' that, when invoked, will call the passed in callback function with some data. Here, a button in the render method allows the user to trigger the sendDataToParent function, enabling communication from the child component back up to its parent.