Paul
Paul

Reputation: 1441

How to set focus on FormControl - Select? (react)

I have material-ui - select and would like to programmatically focus on this element.

<FormControl 
className="select100">
<Select
    ref={(formControll) => { this.formControll = formControll; }}                                 
    native
    value={value}
    input={<Input id="integer" />}
>
    {possibleOptions.map((item, key) => {
      return (<option value={item} key={key}>{item}</option>)
    })}
</Select>

I tried with the ref and write this.formControll.focus(); but react is telling me that focus() is not a function. With a button for example the ref is working.

PS: I don't need autoFocus

Thanks

Upvotes: 4

Views: 5376

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

You can pass the Input inside the Select the autoFocus prop and this will apply to the Select.

<Select
  native
  value={value}
  input={<Input id="integer" autoFocus={true} />}
>
  {possibleOptions.map((item, key) => {
    return (<option value={item} key={key}>{item}</option>)
  })}
</Select>

Edit
When i posted the answer i have missed the part that you don't need the autoFocus.

If you are using an input inside your Select then you can use the inputRef prop and this will focus the underline input "attached" to the select.
Code example and Docs.

Upvotes: 5

raksheetbhat
raksheetbhat

Reputation: 960

<Select
    ref="selectRef"                                 
    native
    value={value}
    input={<Input id="integer" />}
>
    {possibleOptions.map((item, key) => {
      return (<option value={item} key={key}>{item}</option>)
    })}
</Select>

To access, use

this.refs.selectRef.focus()

Here's a reference github link

Upvotes: 2

Related Questions