These might help -
How to Pass Data and Events Between Components in React[
^]
Using Context to pass data[
^]
How to Pass Data from Child to Parent in React[
^]
a Snippet from the last link -
While there is no direct way to pass data from the child to the parent component, there are workarounds. The most common one is to pass a handler function from the parent to the child component that accepts an argument which is the data from the child component.
an Example -
import React from "react";
export default function App() {
return (
<div>
<Parent />
</div>
);
}
Consider a simple application with the App component shown above. It returns a Parent component within a div element. Let’s look at the Parent and Child components.
const Parent = () => {
const [message, setMessage] = React.useState("Hello World");
const chooseMessage = (message) => {
setMessage(message);
};
return (
<div>
<h1>{message}</h1>
<Child chooseMessage={chooseMessage} />
</div>
);
};
const Child = ({ chooseMessage }) => {
let msg = 'Goodbye';
return (
<div>
<button onClick={() => chooseMessage(msg)}>Change Message</button>
</div>
);
};
The initial state of the message variable in the Parent component is set to ‘Hello World’ and it is displayed within the h1 tags in the Parent component as shown. We write a chooseMessage function in the Parent component and pass this function as a prop to the Child component. This function takes an argument message. But data for this message argument is passed from within the Child component as shown. So, on click of the Change Message button, msg = ‘Goodbye’ will now be passed to the chooseMessage handler function in the Parent component and the new value of message in the Parent component will now be ‘Goodbye’. This way, data from the child component(data in the variable msg in Child component) is passed to the parent component.