bug: calling `focus` on an input element inside `componentDidLoad` does not work

Open
#3,246 6 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
typescript
Domain
frontend

Research direction

Reproduce the issue using the input-with-focus.tsx and my-component.tsx examples from the report, then compare the behavior with related issue #1758. Trace the component lifecycle around componentDidLoad and the ref callback; done means the nested input receives focus after the page loads.

Written by the indexing model from the issue text.

Description

Bug: Validated
Prerequisites
Stencil Version

2.14.0

Current Behavior

Calling focus on an input element inside componentDidLoad does not work.

Expected Behavior

The input should be focused after the page load.

Steps to Reproduce
  • npm init stencil
  • Pick component
  • Pick <projectname>
  • cd <projectname>
  • npm install
  • npm run generate
  • Pick input-with-focus
  • Edit input-with-focus.tsx to look like this:
import { Component, Host, h } from '@stencil/core';

@Component({
  tag: 'input-with-focus',
  styleUrl: 'input-with-focus.css',
  shadow: true,
})
export class InputWithFocus {
  inputElement: HTMLInputElement;

  componentDidLoad() {
    this.inputElement.focus();
  }

  render() {
    return (
      <Host>
        <input ref={(el) => { this.inputElement = el; }} placeholder="I should be focused" />
      </Host>
    );
  }
}
  • Edit my-component.tsx to look like this:
import { Component, h } from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true,
})
export class MyComponent {
  render() {
    return (
      <input-with-focus></input-with-focus>
    );
  }
}
  • npm start
  • Observe that the input is not focused
Code Reproduction URL

https://github.com/menelaos/stencil-focus-issue

Additional Information

Possibly related: https://github.com/ionic-team/stencil/issues/1758

Dominant language
TypeScript
Stars
13.1k
Forks
855
Avg merge
4h 7m
Merged PRs (30d)
44

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from stenciljs/core

All issues in stenciljs/core

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.