material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

[TextField] loses focus on rerender

Open domachine opened this issue 11 years ago • 51 comments

If a textfield that had focus, is rerendered by setState, it looses focus.

domachine avatar Jun 08 '15 09:06 domachine

+1

I have to use the onBlur event with defaultValue to get the Textfields working smoothly.

coryasato avatar Jun 19 '15 20:06 coryasato

anyone have a workaround to make this work?

aluksidadi avatar Aug 17 '15 20:08 aluksidadi

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:

4uo63bzhmj

shaurya947 avatar Nov 13 '15 22:11 shaurya947

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}/>

gmadar avatar May 16 '16 07:05 gmadar

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).

liddellj avatar May 31 '16 11:05 liddellj

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.

liddellj avatar May 31 '16 12:05 liddellj

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.

deyceg avatar Jun 26 '16 19:06 deyceg

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.

aesteve avatar Jun 29 '16 05:06 aesteve

Any work around to this? Also noticing this when using a regular input text area inside of a table.

dalexander01 avatar Jul 28 '16 22:07 dalexander01

@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 avatar Jul 29 '16 05:07 deyceg

@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>

Jbarget avatar Aug 05 '16 09:08 Jbarget

I solved it for my case, you need to provide an unique id to that text field. ... The id should not change after re-render though. This way React can keep track of which element was focused or not. P.S. I had textfields in an array which is rendered via myArray.map, there you have to provide same keys when rerender.

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));

ausrasul avatar Oct 17 '16 12:10 ausrasul

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.

manuca avatar Mar 03 '17 00:03 manuca

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.

out

necronet avatar Mar 10 '17 22:03 necronet

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.

cavaloni avatar Mar 17 '17 19:03 cavaloni

Still getting this error. Any work arounds?

JacobSiegel35 avatar Apr 17 '17 21:04 JacobSiegel35

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 avatar Apr 22 '17 13:04 Aspintyl000

@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.

JacobSiegel35 avatar Apr 30 '17 23:04 JacobSiegel35

i am using textfields in a table row, and this is a problem :( any progress?

benjaminhon avatar Jun 29 '17 10:06 benjaminhon

Psid.txt

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.

sugandhhgoyal avatar Jul 24 '17 05:07 sugandhhgoyal