LWC Communication – Child-to-Parent with Examples
When you start Composing components, which is a fancy way of saying adding 1 component inside of another, you have to start thinking of component communication. You might find a need a send data across or might want a certain thing to happen when something changes on the inner component.
Component communication can be classified in 3 types
- Child-to-Parent
- Parent-to-Child
- Non Hierarchical
This post specifically will talk about child-to-parent component communication so lets dive in
Events
Events are the medium through which communication happens. So what is an event really?
Simply put an Event is a notification of change.
It may cause some change in the way the program executes or causes some interesting changes. Some very common examples of event are : mouse hover over , Button click, window resize etc .
In LWC you can communicate using the CustomEvents Interface. There are 3 steps you do create a custom event.
- Create
- Dispatch
- Handle
Scenario
Head count in a mall. We want to keep a track of the foot traffic at a mall. Imagine we have a gate keeping who has out LWC component. Its just has a + and a - button which he/she can click to maintain the active number of visitors in the mall.
Simple Event
This is going to be a very simple component that will have the body count displayed and two button to increase or decrease the count.
Lets see how we can create the event and dispatch it.
addBtnClicked(){
const addButtonEvt = new CustomEvent('add');
this.dispatchEvent(addButtonEvt);
}
substractBtnClicked(){
const subtracrtButtonEvt = new CustomEvent('subtract');
this.dispatchEvent(subtracrtButtonEvt);
}
In the parent component we handling the event
<h3 class="slds-p-around_medium">Total People in the mall are : {peopleCount}</h3>
<c-add-remove-people-count
onadd={addPeople}
onsubtract={subtractPeople}
></c-add-remove-people-count>
Event with Data
In real time scenario we might want to send some data along with the event.
In our second scenario , In our child component we have created a form which would capture the name and email of users and once we submit we are going display it on the parent component
All of the event creation, dispatching and handling is going to be the same except in the event detail property we are going to send the data that we need.
const newEvent = new CustomEvent('formsubmit', {
detail : {
name : this.userName,
email : this.userEmail
}
})
this.dispatchEvent(newEvent);
}
You can find all the code on the github repo