Generic onChange event handler in LWC
Some components have many input components or elements that we need to track in our variables. Creating handler methods for onChange events is the right way to update the variable in our…
Some components have many input components or elements that we need to track in our variables. Creating handler methods for onChange events is the right way to update the variable in our component.
But how can we avoid having multiple handler methods that change only the variable value?
For that, we can use a dynamic generic handler method.
Let’s check an example
markup
<template>
<lightning-input type='text' onchange={handleOnChangeFirstName}>
</lightning-input>
<lightning-input type='text' onchange={handleOnChangeLastName}>
</lightning-input>
<lightning-input type='checkbox' onchange={handleOnChangeIsCompany}>
</lightning-input>
<!-- More input components -->
</template>Don't do this
handleOnChangeFirstName(event) {
this.firstName = event.target.value;
}
handleOnChangeLastName(event) {
this.lastName = event.target.value;
}
handleOnChangeIsCompany(event) {
this.isCompany = event.target.checked;
}
// More handlersInstead, use the data custom attribute with the same name as your component variable.
markup
<template>
<lightning-input data-id="firstName" type='text' onchange={handleOnChangeGeneric}>
</lightning-input>
<lightning-input data-id="lastName" type='text' onchange={handleOnChangeGeneric}>
</lightning-input>
<lightning-input data-id="isCompany" type='checkbox' onchange={handleOnChangeGeneric}>
</lightning-input>
<!-- More input components -->
</template>Do this
handleOnChangeGeneric(event) {
this[event.target.dataset.id] = event.target.value || event.target.checked;
}

