Handle Events on Base Components
Base components come with a rich user interface, where user interactions like a mouse click or a field value change can trigger an event. Handle an event, like click
or change
, by appending an event handler on a base component. The event handler uses the format oneventname
, such as onclick
or onchange
.
Global events that are not explicitly documented may have no effect on the base component, result in regressions, or result in events not firing if the components' internals change in a future release.
A base component can also dispatch a custom event that you can handle, such as the resize
and rowselection
custom events on lightning-datatable
. Review the Documentation tab for a base component in the Component Reference.
Handling an event on a base component is similar to handling an event on an HTML element.
In this example, the val
property renders the text that's entered in the input field by binding its value to event.target.value
.
To dispatch an event from a base component and handle it from a parent component, use the EventTarget.dispatchEvent()
method. For example, say your child component contains a button that handles the click
event. It also dispatches a custom event childbuttonclick
that the parent component can handle.
When you click the button, the handleClick
function dispatches the childbuttonclick
custom event, which you create using new CustomEvent()
.
The parent component listens for the event using the onchildbuttonclick
event handler, since the event is called childbuttonclick
.
To dispatch an event from a base component with data, pass the label: this.buttonLabel
data into the detail
property.
In the parent component, you can get the data using the event.detail.label
syntax.
When you dispatch an event, it can propagate up through the DOM. By default, the event doesn't bubble up nor pass through the shadow boundary. Consider these guidelines when working with events.
- Avoid composed events when you don’t need them.
- If you do need composed events, consider stopping propagation at the intended component.
- Reduce unnecessary event propagation and unintended behaviors.
See Also