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.
Create two lightning web components. Let’s keep the naming convention easy to understand by naming them Parent and Child.
Let’s start with writing all the html and styling in the child component.
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>.
Write the JS code so we can show the attached value from Child to Parent component.
Deploy the code and drag-drop the component on the desired location. Click on save and our component is ready to use.