1

I have a form in an LWC containing a number of lightning-input components and I want the focus to be on the first field when the component initially displays. This works:

async connectedCallback() {

    ...

    // Focus on first input field (once rendering done)
    window.setTimeout(() => {
        const firstInput = this.template.querySelector('lightning-input');
        if (firstInput) firstInput.focus();
    }, 0);
}

but is there a better pattern than using the timeout? (Without the timeout focus is not set.)

The subject is not mentioned in the Lifecycle Hooks documentation.

2

Technically, you can use renderedCallback() to set the focus (which will also cause the focus to shift every time you trigger a render), but doing it the way you are is also perfectly acceptable. The reason why you have to "wait" (via setTimeout) in connectedCallback() is because the component is not actually "fully rendered" at this point in time. See the Lifecycle Flow chart to understand why. The children are rendered after connectedCallback(), and connectedCallback() is called before render() has even been called on the parent.

2
  • Thanks; that flow chart is clearer on the ordering. Perhaps needing an initialRender guard in renderedCallback (in the page I linked to) makes that approach less attractive. – Keith C Mar 17 at 18:27
  • 1
    @KeithC Precisely why I'd use setTimeout for that purpose. Less boilerplate to make it reasonable. – sfdcfox Mar 17 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.