Sub topic 2
`render()`: Choosing Which Template to Show
Assume you know JavaScript classes, LWC templates, reactive properties, and basic DOM events. In LWC, the render() method chooses the template that the component uses. It runs before the selected template is rendered.
Choosing a template with `render()`
Import alternate HTML files and return one based on component state:
import { LightningElement } from 'lwc';
import signedInTemplate from './signedIn.html';
import signedOutTemplate from './signedOut.html';
export default class Greeting extends LightningElement {
isSignedIn = false;
render() {
return this.isSignedIn ? signedInTemplate : signedOutTemplate;
}
}The returned value must be an imported template. Use this pattern when the component has substantially different views. For ordinary conditions inside one view, use template directives such as lwc:if.
What causes a component to render again
LWC renders a component initially, then schedules another render when a reactive value used by its template changes. Common triggers include:
- Assigning a new value to a field used in the template.
- Changing an
@apiproperty from a parent. - Receiving new data from a wire adapter.
- Updating an object or array reference used by the template.
A render is not the same as a browser event. Several state changes may be batched before the next render. Avoid changing reactive state during rendering unless the change is deliberate and guarded.
`renderedCallback()`: Working with the rendered DOM
renderedCallback() runs after the component's DOM has been rendered. It runs after the initial render and after later renders. Use it for DOM-dependent work, such as focusing an input or initializing a third-party widget.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
hasRendered = false;
renderedCallback() {
if (this.hasRendered) {
return;
}
this.hasRendered = true;
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}The guard prevents repeated work. Without it, code that changes reactive state or repeatedly initializes a widget can create unnecessary renders or a render loop.
Hook order across parent and child components
For an initial render, parent creation and connection happen before its child is fully rendered. Rendering callbacks run from the inside out: the child renderedCallback() runs before the parent's renderedCallback().
Exercise
Where should code go if it must query an element created by the component's template?
Show answer
Put it in renderedCallback(), and guard one-time work so it does not repeat on every render.