Is there a recommended approach for focusing a TextField (or any material element for that matter)? I would like to focus a TextField on mount, for example. I tried adding a ref to the component and focusing it that way, but the actual <input>
or <textarea>
is a nested element. Apologies if I missed something in the documentation.
@stevewillard they give className
which I am guessing we could use good old vanilla JS:
document.querySelector('.className input').focus()
Ah, good idea. Thanks, I'll try that!
If that works, I might create a wrapper around TextField that takes a focus or autoFocus prop, which would could do this on prop change or mount.
For anyone curious, it turns you you can simply put the prop autoFocus
(cased like that) on a TextField, and it just works!
<TextField autoFocus />
<TextField autofocus/>
doesn't appear to enable the focus visual state though.
It does for me. It's autoFocus
with a capital F
I stumbled with that a few times myself...
Edit: Whoops. I realized I wrote it wrong in my last message. I updated it.
Yeah, I tried that too. It appears to be due to the tabs/tab hierarchy, since it works for one tab and not the other.
something like:
<Dialog>
<Tabs>
<Tab>
<TextInput autoFocus/>
</Tab>
<Tab>
<TextInput autoFocus/>
</Tab>
</Tabs>
</Dialog>
only tested in FF + Chrome and it breaks for one tab in both browsers. Lazy rendering of the tab content fixes the issue. (Also, why isn't the content lazily rendered in the first place?)
Will come up with a repro example later.
I found about autoFocus but found that it only works when the page first loads, not after form submit. The way I finally found it can be done is by adding a ref to the child TextField and the calling select() on the form submit:
<form onSubmit={this.onSubmit}>
<TextField ref="amountComp" ... />
</form>
and
onSubmit(event: any): void {
// save form
(this.refs["amountComp"] as TextField).select();
};
Most helpful comment
For anyone curious, it turns you you can simply put the prop
autoFocus
(cased like that) on a TextField, and it just works!