How to Pass Data Child to Parent component in React Js (callbackprops)?

Welcome to our new blog, here we will discuss how to Pass Data from Child to Parent in React. To pass data from the child component to the parent component we use callbackprops.

Callbacksprops are a powerful tool in React for passing data between components. Here’s one example:

import React, {useState, useCallback} from "react";

function ParentComponent() {
    const [message, setMessage] = useState(‘Hello, world!’);
    const handleClick = useCallback((newMessage) => setMessage(newMessage), []);

    return (
        <ChildComponent message={message} onClick={handleClick} />
    );

}


function ChildComponent({ message, onClick }) {
  const handleClick = useCallback(() => onClick(‘Hello, callback!’), [onClick]);
  
  return (
    <div onClick={handleClick}>
      {message}
    </div>
  );
  
}

In this example, the state of the parent component holds a message. The parent component also has a handleClick function. when the function is called, it will change the state.

The current message and the handleClick function are passed to the child component as props by the parent component. The child component has a button, when the button is clicked, It calls the props that passed to the handleClick function.