[TextField] loses focus on rerender
If a textfield that had focus, is rerendered by setState, it looses focus.
+1
I have to use the onBlur event with defaultValue to get the Textfields working smoothly.
anyone have a workaround to make this work?
I don't think this an issue any more. See code below:
//taken from examples/webpack-example
/** In this file, we create a React component which incorporates components provided by material-ui */
const React = require('react');
const RaisedButton = require('material-ui/lib/raised-button');
const TextField = require('material-ui/lib/text-field');
const Dialog = require('material-ui/lib/dialog');
const ThemeManager = require('material-ui/lib/styles/theme-manager');
const LightRawTheme = require('material-ui/lib/styles/raw-themes/light-raw-theme');
const Colors = require('material-ui/lib/styles/colors');
const Main = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object,
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
counter: 0,
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500,
});
this.setState({muiTheme: newMuiTheme});
},
componentDidMount() {
this.refs.textField.focus();
},
render() {
console.log(this.state.counter);
let containerStyle = {
textAlign: 'center',
paddingTop: '200px',
};
let standardActions = [
{ text: 'Okay' },
];
return (
<div style={containerStyle}>
<Dialog
title="Super Secret Password"
actions={standardActions}
ref="superSecretPasswordDialog">
1-2-3-4-5
</Dialog>
<h1>material-ui</h1>
<h2>example project</h2>
<TextField ref="textField" onChange = {this._incrementStateCounter}/>
<RaisedButton label="Super Secret Password" primary={true} onTouchTap={this._handleTouchTap} />
</div>
);
},
_handleTouchTap() {
this.refs.superSecretPasswordDialog.show();
},
_incrementStateCounter () {
this.setState({counter: this.state.counter + 1});
},
});
module.exports = Main;
Here's the app in action (with updated state being logged in the console as the TextField input changes). You can see that the TextField retains focus:

I still get this. @shaurya947 example didn't reproduced the bug since the TextField didn't have an initial value property.
to reproduce use
<TextField ref="textField" value={this.state.valueToBeEdited} onChange = {this._incrementStateCounter}/>
or
<TextField ref="textField" defaultValue={this.state.valueToBeEdited} onChange = {this._incrementStateCounter}/>
I am also seeing what appears to be a regression of this issue. My TextFields are losing focus on re-render. I'm setting the value prop of the TextField, so it is a controlled component.
I do notice a new warning in the console: 'TextField is changing an uncontrolled input of type text to be controlled'. I don't recall seeing that before, not sure if it's relevant here or not. The warning appears once I enter the first character into the TextField.
Through a little debugging, it appears that something is causing the TextField to lose focus. The internal onBlur handler is invoked, which toggles the isFocused internal state of the TextField to false. If I log document.activeElement during the onBlur handler (to determine what component has stole focus) then it logs the root of the document (body).
I was able to narrow this down further by determining that the source of the blur event was the first MenuItem within a Menu elsewhere in the app. Setting the disableAutoFocus property to true resolved my issue. Hope this helps someone else.
I've opened a separate issue to capture this: #4387.
I can confirm this is still an issue...
Seeing it in a very simple login form - I'm using this in conjunction with redux forms and when I interact with the form it causes a re-render (touched a field in redux-form parlance) which loses the focus.
As a workaround, I'm only re-rendering the actual form if there been a change in the error state.
You can reproduce this issue easily by putting the TextField within a Table set as selectable=true. Whenever you click on a text field to start editing it, the line will get the focus, thus change its background color (I guess some props of the line might be set as selected=true), thus trigger a re-render, thus you'll lose the focus...
So you basically can't use a TextField within a selectable Table, not sure it's a good UX practice anyway, but still :)
We noticed that on our project, I can try to push a reproducer.
Any work around to this? Also noticing this when using a regular input text area inside of a table.
@dalexander01 Found a "solution", but it seems very redux-form specific as was experiencing the same problem when not using md input components. If its of any use I can post a snippet!
@deyceg please do, it cant hurt 😄 . Just run into this issue with this combination of a <Dialog/> and a <TextField/>.
<Dialog
open={this.props.showDialog}
title={'New ' + this.props.type}
autoScrollBodyContent={true}
actions={actions}
bodyStyle={styles.dialogContent}
>
<SelectField
name='sub_type'
value={this.props.top_card.sub_type}
onChange={(e, k, payload) => this.props.topCardSelectChange('sub_type', payload)}
floatingLabelText='Type'
>
{menuItemsJSX}
</SelectField>
<TextField
name='title'
className='story-title'
value={this.props.top_card.title}
onChange={this.props.topCardChange}
floatingLabelText='Title'
fullWidth={true}
multiLine={true}
style={styles.title}
/>
<TextField />
</Dialog>
I solved it for my case, you need to provide an unique id to that text field.
EDIT: I tested again, just having the "key" on myArray to be the same across rerenders solved the issue. The textfield id changed to shortid.generate().
params.map(function(p,i){
return(
<div key={i}> <--- this will always be the same for this particular row.
<div className='param-inner'>
<TextField id={shortid.generate()} value = {p.value} onChange={this.updateParam.bind(this,i)}/> <-- id here can be random, but it is necessary to avoid browser warning "we don't have enough information..."
</div>
<div className='param-inner'>{p.unit}</div>
</div>
)
}.bind(this));
Anyone managed to find a workaround this issue (without using refs)? It seems to be the combination of onChange and setting the value prop to a state key that makes the input loose focus.
I had the following issue too, I solved it though by having taking the SelectField implementation if you see it internally is calling a DropdownMenu https://github.com/callemall/material-ui/blob/ccf712c5733508784cd709c18c29059542d6aad1/src/SelectField/SelectField.js#L192
so I also need it to add a DropDownMenu this internally is wrapping the components in a Menu, I added disableAutoFocus to make my TextField keep the focus on it as show bellow.
Maybe we can expose a DropDownMenu component from the SelectField and allow autofocus to be disable with props.

One workaround for this for those who are struggling with it and just want something to work, though its possible its likely not applicable in some situations and could present issues (I am not entirely certain myself though) is to use a variable on the instance rather than the state. So instead of this.state.value it would be this.value that onChange would be updating. The component would not have a value prop. Then on the onChange handler you would use e.target.value.
The only difference I know of between a variable on the instance vs. the state is that the instance var will not trigger a re-render. Though there could be other reasons so I'm hoping other's will catch my slack on this one.
Still getting this error. Any work arounds?
The workaround I found was to override the shouldComponentUpdate function to my component and then return false when I changed the state values used by my textfields.
`shouldComponentUpdate(nextProps, nextState) {
if(nextState.email != this.state.email) {
return false;
}
else if(nextState.password != this.state.password) {
return false;
}
else return true;
}
`
Doing it this way fixed my issue. The issue seems to be the component rendering every time the state changes which then resets focus. So by using the above function to disable rendering when you do an onChange event to set state values the component doesn't reload.
@Aspintyl000 this works... somewhat. When I am setting the value of the textfield through the 'value' prop, and I am setting that prop to 'this.state.value', nothing shows up. Although, when I remove that, it seems to work.
i am using textfields in a table row, and this is a problem :( any progress?
I was also getting the same error . But after using componentDidMount() { this.refs.textField.focus(); } it does not lose focus. But it does not show the input value.