Communication Between Components In React

In this blog, I will briefly cover how does communication works between components in React (Child to Parent) as it is one of the essential concepts in React. Let's get started.

First of all, passing data will be between a child component and a parent component; for instance, let's assume that we have three components which are the App(root), Parent, and a Child component. Now we want to get a submitted form data from the child to the root. It will take a 2 step process which is passing data from child to parent, and from that parent to the root one. Now let's see the code part to clarify the point.

// Parent Component

import Child from './Child'

export default Parent(props) {

const formDataHandler = (data) {
 console.log(data) // 'Hello World'
}

 return (
  <Child  onSaveFormData={formDataHandler} />
 )

}

We wrote a function that is responsible for receiving the data. But how will this function be invoked? Well, we will point this function as a prop to the child component in order to be able to call that function from that child component, so when this function is invoked in the child element we will be able to use that data from the parent.


export default Child(props) {

// Child Component

 let data = 'Hello World'

 // calling the function in the parent component
 function submitHandler() {
 props.onSaveFormData(data);
 } 

return (
 <form onSubmit={submitHandler} > </form>
)

}

Now I think you understood the concept of this pattern which is passing data through invoking functions that are passed as a prop in the parent component, and the time invoking this function will depend on your idea, so in our case here, will are invoking it when the form is submitted

Didn't get the idea, don't worry we will repeat this again to pass the data to the App component.

// App Component

import Parent from './Parent'

function App() {

function formData(data) {
  console.log(data)
}

return ( 
 <Parent getFormData= {formData} />
)

}

Now we will invoke the function in the Parent component inside the function that the Child component has just invoked

// Parent Component

import Child from './Child'

export default Parent(props) {

const formDataHandler = (data) {
 props.getFormData(data)
}

 return (
  <Child  onSaveFormData={formDataHandler} />
 )

}

And that's all about communication between Childs and Parents. Stay tuned for the next blog which we will cover ways of passing data from Parent to Child.

Did you find this article valuable?

Support Ahmed Essam by becoming a sponsor. Any amount is appreciated!