It is possible to focus Textfields, buttons with a ref. This isn't working with select.
I do not mean autoFocus. I want to focus on a select field when a user clicks on a button.
My code:
<FormControl
className="select100">
<Select
ref={(formControll) => { this.formControll = formControll; }}
native
value={aValue}
input={<Input id="integer" />}
>
{possibleOptions.map((item, key) => {
return (<option value={item} key={key}>{item}</option>)
})}
</Select>
</FormControl>
If I now try to set the focus on the select with:
this.formControll.focus();
it isn't working.
| Tech | Version |
|--------------|---------|
| Material-UI | 1.0.0-beta.24 |
| React | 16.2.0 |
| browser | Chrome |
Please reserve issues for issues with material ui. If you have questions, please try StackOverflow.
That said, you need to use the inputRef property of the Input component. See this codesandbox:
<FormControl className="select100">
<Select
native
value={aValue}
input={
<Input
id="integer"
inputRef={formControll => {
this.formControll = formControll;
}}
/>
}
>
{possibleOptions.map((item, key) => {
return (
<option value={item} key={key}>
{item}
</option>
);
})}
</Select>
</FormControl>
I just took your code, hardcoded aValue and possibleOptions, and added componentDidMount:
componentDidMount(){
if (this.formControll) {
this.formControll.focus();
}
}
I tried above solution for MUI 3.4.0
But it is not working
@sedi0861 Try: https://codesandbox.io/s/505nl3x85p
@joshwooding I need the focus when the component loading.
I tried adding
componentDidMount() {
this.handleFocus();
}
But it is not working.
@sedi0861 Sorry, check https://codesandbox.io/s/y79j9x8421
For your case I would use autoFocus
@joshwooding I tried autoFocus but it is not working for me.
And I tried the method in https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
It doesn't work either. https://codesandbox.io/s/q8vy3lylrj
@sedi0861 https://codesandbox.io/s/8nj6jz8n38 If I change handleFocus to use your textInput ref it works
@joshwooding Oh wow. great! Thanks. How could that happen? handleFocus did not have any effect on componentDidMount?
@sedi0861 It does? https://codesandbox.io/s/y79j9x8421
it didn't work for me, I used a controlled component https://codesandbox.io/s/inspiring-engelbart-osjok?file=/src/App.js
Most helpful comment
@sedi0861 https://codesandbox.io/s/8nj6jz8n38 If I change handleFocus to use your textInput ref it works