12

I use Material-UI TextField

I want to implement an autofocus, I can't find a way to do it from markup by setting autofocus=true not programmatically. any help?

Amr M. AbdulRahman
  • 1,671
  • 3
  • 13
  • 22
  • 2
    Possible duplicate of [How to set focus to a materialUI TextField?](https://stackoverflow.com/questions/37949394/how-to-set-focus-to-a-materialui-textfield) – Lane Rettig Jun 16 '17 at 11:03

3 Answers3

30

You can do this like this: <TextField autoFocus></TextField>.

More on this: https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes.

Richard
  • 14,029
  • 9
  • 53
  • 83
Deividas Karzinauskas
  • 6,243
  • 2
  • 25
  • 26
5

For some reason this was not working for me (maybe because it's within a component that's not visible when the top-level component mounts). I had to do something more convoluted to get it to work:

const focusUsernameInputField = input => {
  if (input) {
    setTimeout(() => {input.focus()}, 100);
  }
};

return (
  <TextField
    hintText="Username"
    floatingLabelText="Username"
    ref={focusUsernameInputField}
  />
)

For more info see https://github.com/callemall/material-ui/issues/1594.

Lane Rettig
  • 6,175
  • 4
  • 40
  • 49
  • 1
    "...The element must be visible in order to be focusable. Elements of the following type are focusable if they are not disabled: input, select, textarea, button, and object. Anchors are focusable if they have an href or tabindex attribute. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map. All other elements are focusable based solely on their tabindex attribute and visibility.": From https://api.jqueryui.com/focusable-selector/ – jobmo Oct 06 '17 at 09:15
0

I just simply put the ref of input into state

<TextInput inputRef={el => { this.setState({form: el}) }}/>

then you can set focus to the input anywhere.

this.state.form.focus()