In this blog we will see how to communicate from one LWC to another LWC and pass the data.

Why Multiple Components?

Now the question is why do we need two different components when we can complete the requirement in one single component? So right now the requirement is simple to pass a value from one component to another but if the requirement is more than that, doing all this in a single component can be a disaster because of the complexity and lines of code.

And if we want to modify it we have to search from hundreds of lines of code to get that particular block and then modify it.

That is the reason why we create multiple components, each with a different purpose to fulfil and it’s easy to maintain and modify.

Step 1:

Create two lightning web components. Let’s keep the naming convention easy to understand by naming them Parent and Child.

Step 2:

Let’s start with writing all the html and styling in the child component.

Step 3:

Write the Javascript code for our Child component which will create an event and the event then will be cached by our parent component. Also, the data we want to communicate from child to parent is also attached to this event.

Step 4:

Let’s add the HTML and styling to our Parent component and also catch the event we fired from our Child component by appending ‘on’ in before the event name.

We are also going to place our Child component inside our parent component by using <c-componentname></c-componentname>. So in our case it would be <c-child></c-child>.

Step 5:

Write the JS code so we can show the attached value from Child to Parent component.

Step 6:

Deploy the code and drag-drop the component on the desired location. Click on save and our component is ready to use.

Request a Free Consultation

YOU MIGHT ALSO LIKE