How to autofocus an input field in semantic-ui-react?

Matt MacPherson picture Matt MacPherson · Mar 8, 2018 · Viewed 7.1k times · Source

I'm having a difficult time autofocusing an input field with semantic-ui-react. The documentation doesn't seem to include an autoFocus prop and the focus prop doesn't place the cursor inside the input field as would be expected.

<Form onSubmit={this.handleFormSubmit}>
  <Form.Field>
    <Form.Input
      onChange={e => this.setState({ username: e.target.value })}
      placeholder='Enter your username'
      fluid />
  </Form.Field>
</Form>

EDIT: This code works:

<Form onSubmit={this.handleFormSubmit}>
  <Form.Input
    onChange={e => this.setState({ username: e.target.value })}
    placeholder="Enter your username"
    autoFocus
    fluid />
</Form>

Answer

Tydax picture Tydax · Mar 12, 2018

The focus prop is purely to add a focus effect on the input's appareance, it does not actually set the focus.

Any props unused by Semantic are passed down to the DOM element, so if you set an autoFocus prop, it should go down to the input.

However, as explained in the Form documentation:

Form.Input

Sugar for <Form.Field control={Input} />.

So your code should rather be:

const yourForm = (
  <Form onSubmit={this.handleFormSubmit}>
    <Form.Input
      onChange={e => this.setState({ username: e.target.value })}
      onSelect={() => this.setState({ usernameErr: false })}
      placeholder="Enter your username"
      error={usernameErr}
      iconPosition="left"
      name="username"
      size="large"
      icon="user"
      fluid
      autoFocus
    />
  </Form>
)

Note that this only works if you want the focus to happen right when the wrapper component is mounted. If you want to focus the input after it has been mounted, you have to use a ref and call the focus() method on it, just as showed in the documentation, like so:

class InputExampleRefFocus extends Component {
  handleRef = (c) => {
    this.inputRef = c
  }

  focus = () => {
    this.inputRef.focus()
  }

  render() {
    return (
      <div>
        <Button content='focus' onClick={this.focus} />
        <Input ref={this.handleRef} placeholder='Search...' />
      </div>
    )
  }
}

Hope that helps!