Sub topic 16
Using Lightning base components
What you need first
This chapter assumes you can read an LWC bundle: an HTML template, a JavaScript class, @api properties, and CustomEvent handlers. It also assumes you know that each component renders inside a shadow root. Earlier chapters covered these.
What base components are
Base components are prebuilt Lightning Web Components that Salesforce ships in the lightning namespace. You use them like HTML tags, and the tag name is the component name in kebab-case:
lightning-buttonlightning-inputlightning-cardlightning-formatted-number
Base components follow the same rules as components you write. Each is a custom element with a shadow root. You set its public properties as attributes, and it sends events that you listen for with on-prefixed handlers. The only new part is that someone else wrote and maintains the component.
Base components exist only on the Salesforce platform. The open-source LWC project does not include the lightning namespace. If you build with open-source LWC outside Salesforce, you write these pieces yourself or use another library.
Why use them
- Consistent look. They apply the Salesforce Lightning Design System (SLDS) styles, so your UI matches the rest of the page.
- Accessibility. Labels, keyboard handling and ARIA attributes are built in.
- Locale handling. Formatting components such as
lightning-formatted-numberandlightning-formatted-date-timefollow the user's locale and currency settings. - Less code. A validated input with a label, a required marker and an error message is one tag.
A worked example
This component uses a card, a text input and a button. The user types a name, and the component validates it and then shows a greeting.
<!-- greetingCard.html -->
<template>
<lightning-card title="Greeting" icon-name="standard:contact">
<div class="slds-var-p-around_medium">
<lightning-input
label="Your name"
value={name}
required
onchange={handleChange}
></lightning-input>
<lightning-button
class="slds-var-m-top_small"
variant="brand"
label="Greet"
onclick={handleGreet}
></lightning-button>
<template lwc:if={message}>
<p class="slds-var-m-top_small">{message}</p>
</template>
</div>
<p slot="footer">Powered by base components</p>
</lightning-card>
</template>// greetingCard.js
import { LightningElement } from 'lwc';
export default class GreetingCard extends LightningElement {
name = '';
message = '';
handleChange(event) {
this.name = event.target.value;
}
handleGreet() {
const input = this.template.querySelector('lightning-input');
if (!input.reportValidity()) {
return;
}
this.message = `Hello, ${this.name}!`;
}
}<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>This one example uses most of the ideas in the chapter.
Attributes map to public properties
icon-name in the template sets the iconName property on lightning-card. HTML attribute names are lowercase, so the compiler converts kebab-case to camelCase. The same rule applies to your own @api properties. A property named iconName is set with icon-name.
Events follow the standard model
lightning-input fires a change event, and you listen with onchange. The new value is on event.target.value. For a checkbox input (type="checkbox") you read event.target.checked instead. lightning-button fires a standard click event.
Slots work as they do in your own components
lightning-card has a default slot for the body, plus named slots such as actions and footer. The <p slot="footer"> line puts content in the footer slot. This is the same slot mechanism from the composition chapter.
Methods are public API too
reportValidity() is an @api method on lightning-input. You get a reference with this.template.querySelector, then call the method. The method shows the error message on the field and returns true or false. A checkValidity() method also exists. It returns the same result but does not show the message.
What the rendered tree looks like
Your component's shadow root holds the base component elements. Each base component has its own shadow root with its own markup.
Your code cannot see the native <input> inside lightning-input. You only talk to the outer element through its attributes, methods and events.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Writing `iconName="..."` in the template | The attribute is not matched to the property | Use `icon-name="..."` |
| Querying `this.template.querySelector('input')` for the native input | Returns `null` because the input is inside another shadow root | Query `lightning-input` and use its public API |
| Using CSS from your component to restyle internals | Styles do not cross the shadow boundary | Use the component's `variant` options, SLDS utility classes on the host, or styling hooks |
| Reading `event.target.value` for a checkbox | Gets the wrong data | Read `event.target.checked` |
| Using `lightning-*` tags in open-source LWC | The element is never defined and nothing renders | Build the element yourself or use another library |
| Calling `reportValidity()` on a component that does not have it | A runtime error | Check the component's reference page for its public methods |
Styling base components
Style scoping blocks selectors like lightning-input input { ... } from reaching inside. You have these options:
- Use built-in attributes such as
variant,sizeandalternative-text. - Apply SLDS utility classes, such as
slds-var-m-top_small, to the base component's host element. In the example above, the button gets a margin class this way. - Use CSS custom properties called styling hooks, where a component documents them. They are the only supported way to change internal colors and spacing.
Avoid trying to pierce the shadow boundary with tricks. They break when Salesforce updates the component's internal markup.
Choosing between base and custom
Use a base component when it already does the job. Write your own when you need markup the base component does not allow, or when the component must run outside Salesforce. Even then, you can wrap a base component in your own component and expose only the properties you want. Callers of your wrapper depend on your @api surface and not on the base component's.
Summary of what is standard
A base component is an ordinary custom element with a shadow root, public properties, events and slots. The lightning namespace, the SLDS styling and the locale support are Salesforce additions. Nothing about using them requires a new concept beyond what the standards and LWC already give you.
Exercise
A teammate writes this.template.querySelector('input').focus() to focus the field inside a <lightning-input> and gets an error because the result is null. Why does this happen, and what should they do?
Show answer
The native <input> lives inside the shadow root of lightning-input, and querySelector on this.template only searches your component's own shadow root. They should query lightning-input instead and call its public focus() method: this.template.querySelector('lightning-input').focus().
Exercise
You set <lightning-card iconName="standard:account"> and no icon appears. What is wrong, and what is the correct markup?
Show answer
In templates, attribute names must be kebab-case, and the compiler maps them to camelCase properties. The correct markup is <lightning-card icon-name="standard:account">.