1

I'm trying to use focus to point to specific section on the page and it returns the above error on page load.

@api objError;
    connectedCallback(){
        /* eslint-disable no-console */
        console.log('objError in child : ',this.objError.id);
        this.template.querySelector('[data-id="${this.objError.id}"]').focus();
    }

I'm setting the objError value from the parent component which holds the id and type properties.

Id value in objError record passed to the component matches the data-id value of one of the input fields on the template.

I first tried with : this.template.querySelector('[data-id="{this.objError.id}"]').focus();

but that didn't work either.

I have tried to console and print the values in parent component held by objError independently and that displays the values as expected. I'm not sure why it's returning null for the same value in child component.

How can I resolve this issue?

1

To use the "merge field syntax", as I've heard it called elsewhere, you need to use a template literal. In JavaScript, we do this by using the backtick character instead of a normal apostrophe or quotation mark.

this.template.querySelector(`[data-id="${this.objError.id}"]`).focus();
0

On Top of sfdcfox response - at this lifecycle phase the element is not inserted yet into the DOM which means you always get a null reference.

To sum up:

  1. move your query selector to the renderedCallback hook (potentially with a helper variable to focus the input once instead of every rerender)
  2. Fix the syntax in your query to use backticks

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.