0

I encountered a very odd behaviour which I don't understand. My component has the following code :

myFocusOnRender = false;

handleResultClick(event) {
   this.myFocusOnRender = true;
   ...
}

renderedCallback(){
        if(this.myFocusOnRender){
            input.focus();
            this.myFocusOnRender = false;
        }
}

The issue is that when the renderedCallback is triggered, my attribute myFocusOnRender is false however it is not set to false by any line in my component.

Do you have any clue about that ?

Thank you in advance,

4
  • 1
    You defaulted it to false on the first line in your code example? – sfdcfox May 3 at 14:37
  • Yes but it is set to true in my handler and this handler trigger the rendering – Ombrelin May 3 at 14:42
  • The LWC's initial rendering isn't something you trigger, it happens naturally. – Phil W May 3 at 16:22
  • When I say trigger, I mean the method updated reactive properties which triggers the component rendering. Sorry if it wasn’t clear – Ombrelin May 3 at 17:01
0

Okay so after a thorough investigation, we found out that the component was disconnected from its parent and then reattached, I don't understand why since it's only supposed to be a rerender, but here is the workaround we came up with :

On the child component, have an event dispatched and a public @api method to focus the input :

handleResultClick(event) {
  this.dispatchEvent(new CustomEvent("focuslost"))
   ...
}

    focusInput(){
        this.template.querySelector(".slds-input").focus();
    }

And in the parent, call the method in a handler, with a setTimeout, in order to push the execution of the code behind the component lifecycle method on the event loop :

    handleFocusLost() {
        setTimeout(() => this.template.querySelector('c-lookup').focusInput(), 0)
    }

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.